# Nginx / PHP / MySQL



## Installer un serveur web



#### Installer Nginx:

```bash
$ sudo apt-get install nginx
```

##### Version de Nginx:

```bash
$ nginx -v
nginx version: nginx/1.14.0 (Ubuntu)
```

##### Démarrer,activer et vérifier l'étât du service Nginx.

```bash
$ sudo systemctl start nginx.service
$ sudo systemctl enable nginx.service
$ sudo systemctl status nginx.service
```

```bash
# ps -ef | grep -i nginx

root     18596 13:16 nginx: master process ./nginx
nobody   18597 13:16 nginx: worker process
```



https://www.nginx.com/resources/wiki/start/

https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/

https://wiki.debian.org/Nginx/DirectoryStructure

##### Arborescence:

```bash
bruno@MintBook:/etc/nginx$ tree
.
├── conf.d
├── fastcgi.conf
├── fastcgi_params
├── koi-utf
├── koi-win
├── mime.types
├── modules-available
├── modules-enabled
│   ├── 50-mod-http-geoip.conf -> /usr/share/nginx/modules-available/mod-http-geoip.conf
│   ├── 50-mod-http-image-filter.conf -> /usr/share/nginx/modules-available/mod-http-image-filter.conf
│   ├── 50-mod-http-xslt-filter.conf -> /usr/share/nginx/modules-available/mod-http-xslt-filter.conf
│   ├── 50-mod-mail.conf -> /usr/share/nginx/modules-available/mod-mail.conf
│   └── 50-mod-stream.conf -> /usr/share/nginx/modules-available/mod-stream.conf
├── nginx.conf
├── proxy_params
├── scgi_params
├── sites-available
│   └── default
├── sites-enabled
│   └── default -> /etc/nginx/sites-available/default
├── snippets
│   ├── fastcgi-php.conf
│   └── snakeoil.conf
├── uwsgi_params
└── win-utf
```

##### Configuration:

Le fichier `/etc/nginx/nginx.conf` contient la configuration générale de nginx.

```nginx
user www-data;
```



Créer un fichier qui contiendra les configurations du site dans le répertoire `/etc/nginx/sites-available/`.
Le dossier contient déjà un fichier par défaut: `/etc/nginx/sites-available/default`

```bash
$ cd /etc/nginx/sites-available/
$ sudo cp default mint
$ sudo gedit mint
```

Modifier les lignes:

- root: le dossier root du site
- index: ajouter index.php
- server_name

Dé-commenter les lignes:

- include snippets/fastcgi-php.conf;
- fastcgi_pass unix:/run/php/php7.2-fpm.sock;

```nginx
server {
	listen 80 default_server;
	listen [::]:80 default_server;

	# SSL configuration
	#
	# listen 443 ssl default_server;
	# listen [::]:443 ssl default_server;
	#
	# Note: You should disable gzip for SSL traffic.
	# See: https://bugs.debian.org/773332
	#
	# Read up on ssl_ciphers to ensure a secure configuration.
	# See: https://bugs.debian.org/765782
	#
	# Self signed certs generated by the ssl-cert package
	# Don't use them in a production server!
	#
	# include snippets/snakeoil.conf;

	root /home/bruno/Sites;

	# Add index.php to the list if you are using PHP
	index index.php index.html index.htm;

	server_name mintbook.local;

  access_log /var/log/nginx/access_log;
	error_log /var/log/nginx/error_log;
  
	location / {
		# First attempt to serve request as file, then
		# as directory, then fall back to displaying a 404.
		try_files $uri $uri/ =404;
	}

	# pass PHP scripts to FastCGI server
	#
	location ~ \.php$ {
		include snippets/fastcgi-php.conf;
	#
	#	# With php-fpm (or other unix sockets):
		fastcgi_pass unix:/run/php/php7.2-fpm.sock;
	#
	#	# With php-cgi (or other tcp sockets):
	#	fastcgi_pass 127.0.0.1:9000;
	}

	# deny access to .htaccess files, if Apache's document root
	# concurs with nginx's one
	#
	#location ~ /\.ht {
	#	deny all;
	#}
}
```



Donner les droits à Nginx pour le dossuier root:

```bash
$ sudo chown -R www-data:www-data /home/bruno/Sites
```



Déclarer le socket Unix de PHP-FPM au niveau de Nginx: il faut modifier ou créer le fichier `/etc/nginx/conf.d/php7-fpm.conf`

```nginx
upstream php7.2-fpm-sock {
        server unix:/run/php/php7.2-fpm.sock;
}
```



Créer ensuite un lien symbolique de ce fichier dans le répertoire `/etc/nginx/sites-enabled/` afin d’activer le site.

 Il est à noter que pour désactiver le site temporairement il suffit de supprimer le lien symbolique qui est dans `sites-enabled` et pour le réactiver, il faut refaire un lien symbolique avec le fichier qui se trouve dans `site-available`.

```bash
$ cd  /etc/nginx/sites-enabled/
$ ln -s /etc/nginx/sites-available/mint  mint

$ ls -la
total 8
drwxr-xr-x 2 root root 4096 mai   30 12:56 .
drwxr-xr-x 8 root root 4096 mai   30 10:40 ..
lrwxrwxrwx 1 root root   34 mai   30 10:40 default -> /etc/nginx/sites-available/default
lrwxrwxrwx 1 root root   31 mai   30 12:56 mint -> /etc/nginx/sites-available/mint

$ sudo rm default
```



##### Tester la configuration Nginx:

```bash
$ sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
```

##### Relancer Nginx:

```bash
$ sudo service nginx reload
```



##### Commandes Nginx:

Démarrer nginx:  `$ sudo systemctl start nginx`

Arrêter nginx: `$ sudo systemctl stop nginx`

Redémarrer nginx: `$ sudo systemctl restart nginx`

Recharger nginx après une modification de configuration: `$ sudo systemctl reload nginx`

Désactiver le démarrage auto de nginx avec le système: `$ sudo systemctl disable nginx`

Activer le démarrage auto de nginx avec le système: `$ sudo systemctl enable nginx`



##### Vérifier l'étât de Nginx:

```bash
$ systemctl status nginx
● nginx.service - A high performance web server and a reverse proxy server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
   Active: active (running) since Thu 2019-05-30 10:40:04 CEST; 21h ago
     Docs: man:nginx(8)
 Main PID: 19485 (nginx)
    Tasks: 9 (limit: 4915)
   CGroup: /system.slice/nginx.service
           ├─19485 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
           ├─30594 nginx: worker process
           ├─30595 nginx: worker process
           ├─30596 nginx: worker process
           ├─30597 nginx: worker process
           ├─30598 nginx: worker process
           ├─30599 nginx: worker process
           ├─30600 nginx: worker process
           └─30601 nginx: worker process

```



#### HTTPS:

https://linoxide.com/linux-how-to/create-self-signed-ssl-certificate-nginx-ubuntu/

https://www.digitalocean.com/community/tutorials/how-to-create-a-self-signed-ssl-certificate-for-nginx-in-ubuntu-18-04



##### Créer une clé et un certificat. auto-signé:

```bash
$ sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/ssl/private/mintbook.local.key -out /etc/ssl/certs/mintbook.local.crt
[sudo] password for bruno:          
Generating a 2048 bit RSA private key
...........+++
.................+++

## writing new private key to '/etc/ssl/private/mintbook.local.key'

You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,

## If you enter '.', the field will be left blank.

Country Name (2 letter code) [AU]:FR
State or Province Name (full name) [Some-State]:Bourgogne
Locality Name (eg, city) []:Dijon
Organization Name (eg, company) [Internet Widgits Pty Ltd]:clicclac.info
Organizational Unit Name (eg, section) []:Web
Common Name (e.g. server FQDN or YOUR name) []:mintbook.local
Email Address []:enzo@clicclac.info

```

##### Paramètres Diffie-Hellman (DH):

```
$ sudo openssl dhparam -out /etc/ssl/certs/dhparam.pem 2048
Generating DH parameters, 2048 bit long safe prime, generator 2
This is going to take a long time
..........................................+.....+..

```

##### Configuration SSL:

```bash
$ sudo nano /etc/nginx/snippets/self-signed.conf

```

```ini
ssl_certificate /etc/ssl/certs/mintbook.local.crt;
ssl_certificate_key /etc/ssl/private/mintbook.local.key;

```



```bash
$ sudo nano /etc/nginx/snippets/ssl-params.conf

```

```ini
ssl_protocols TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_dhparam /etc/ssl/certs/dhparam.pem;
ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384;
ssl_ecdh_curve secp384r1; # Requires nginx >= 1.1.0
ssl_session_timeout  10m;
ssl_session_cache shared:SSL:10m;
ssl_session_tickets off; # Requires nginx >= 1.5.9
ssl_stapling on; # Requires nginx >= 1.3.7
ssl_stapling_verify on; # Requires nginx => 1.3.7
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 5s;

# Disable strict transport security for now. You can uncomment the following

# line if you understand the implications.

# add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";

add_header X-Frame-Options DENY;
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";

```



```bash
$ cd /etc/nginx/sites-available
$ sudo cp mint mint-ssl
$ sudo gedit mint-ssl 

```

```ini
# SSL configuration
#
listen 443 ssl default_server;
listen [::]:443 ssl default_server;
#
# Note: You should disable gzip for SSL traffic.
# See: https://bugs.debian.org/773332
#
# Read up on ssl_ciphers to ensure a secure configuration.
# See: https://bugs.debian.org/765782
#
# Self signed certs generated by the ssl-cert package
# Don't use them in a production server!
#
# include snippets/snakeoil.conf;
include snippets/self-signed.conf;
include snippets/ssl-param.conf;

```

#### Installer PHP:

```bash
$ sudo apt-get install php-fpm

```

```bash
$ which php
/usr/bin/php

$ php -v
PHP 7.2.17-0ubuntu0.18.04.1 (cli) (built: Apr 18 2019 14:12:38) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.2.17-0ubuntu0.18.04.1, Copyright (c) 1999-2018, by Zend Technologies

```



##### Configurer PHP-FPM:

- PHP et Nginx sur la même machine => socket Unix
- PHP et Nginx sur la même machine => socket TCP



```bash
$ sudo gedit /etc/php/7.2/fpm/pool.d/www.conf

```

Vérifier que PHP-Fpm utilise le Socket Unix (NGINX et PHP sur la même machine):

```bash
;listen = 127.0.0.1:9000
listen = /run/php/php7.2-fpm.sock

```



##### Configurer PHP.ini:

```bash
$ nano /etc/php/7.2/fpm/php.ini

```

```ini
file_uploads = On
allow_url_fopen = On
memory_limit = 256M
upload_max_filesize = 64M
cgi.fix_pathinfo = 0
upload_max_filesize = 100M
max_execution_time = 360
date.timezone = Europe/Paris

```

*cgi.fix_pathinfo : l’activation de ce paramètre permet à PHP de n’accepter que les URI qui existent réellement sur le serveur.*



##### Configurer Nginx:

```bash
$ sudo gedit /etc/nginx/sites-availables

```

Activer php:

```nginx
location ~ \.php$ {
	include snippets/fastcgi-php.conf;
#
#	# With php-fpm (or other unix sockets):
	fastcgi_pass unix:/run/php/php7.2-fpm.sock;
#
#	# With php-cgi (or other tcp sockets):
#	fastcgi_pass 127.0.0.1:9000;
}

```

Redémarrer le service php-fpm:

```bash
$ sudo service php7.2-fpm restart

```



##### Installer les modules PHP manquants:

Dans le Gestionnaire de paquets Synaptic, installer les modules GD, MySQL...

Manque: apcu, gmp, odbc, yaml

ou

```bash
$ sudo apt-cachesearch php- | less
$ sudo apt-get install "module name"
$ sudo apt-cache show "module name"

```



#### Installer MySQL (MariaDB):

```bash
$ sudo apt-get -y install mariadb-server mariadb-client

```

##### Démarrer, activer et vérifier l'étât du service MariaDB:

```bash
$ sudo systemctl start mysql.service
$ sudo systemctl enable mysql.service
$ sudo systemctl status mysql.service

```



##### Securiser l'installation de MariaDB:

```bash
$ sudo mysql_secure_installation

Enter current password for root (enter for none): Enter Your Current Password
OK, successfully used password, moving on...

Set root password? [Y/n] n
 ... skipping.

Remove anonymous users? [Y/n] y
 ... Success!

Disallow root login remotely? [Y/n] y
 ... Success!

Remove test database and access to it? [Y/n] y

- Dropping test database...
  ... Success!
- Removing privileges on test database...
  ... Success!

Reload privilege tables now? [Y/n] y
 ... Success!

Cleaning up...

All done!  If you've completed all of the above steps, your MariaDB
installation should now be secure.

Thanks for using MariaDB!

```

~~l/p: root/sncfp1p2~~



##### Désinstaller mysql:

```bash
    $ sudo service mysql stop
    $ sudo apt-get remove --purge mysql*
    $ sudo apt-get autoremove
    $ sudo apt-get autoclean
    $ sudo rm -rf /var/lib/mysql
    $ sudo rm -rf /etc/mysql

```



##### Se connecter à MySQL:

```bash
$ sudo mysql -u root -p
Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 49
Server version: 10.1.38-MariaDB-0ubuntu0.18.04.2 Ubuntu 18.04

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> 

```



##### Depuis ubuntu 18.04

Se logguer dans mysql en root.

Créer un utilisateur et lui donner tous les droits:

```mysql
CREATE USER 'username'@'localhost' IDENTIFIED BY 'the_password';
GRANT ALL PRIVILEGES ON *.* TO 'username'@'localhost' WITH GRANT OPTION;

```

Créer un utilisateur avec le même nom et lui donner tous les droits:

```mysql
CREATE USER 'username'@'%' IDENTIFIED BY 'the_password';
GRANT ALL PRIVILEGES ON *.* TO 'username'@'%' WITH GRANT OPTION;

```

Le compte 'username'@‘localhost' est utilisé quand on se connecte depuis la machine locale.
Le compte 'username'@'%' est utilisé pour se connecter depuis n'importe quelle machine.

```mysql
SHOW GRANTS FOR username;
FLUSH PRIVILEGES;

```



#### Configurer le firewall ubuntu:

```bash
$ sudo ufw app list
[sudo] password for bruno:          
Available applications:
  CUPS
  Nginx Full
  Nginx HTTP
  Nginx HTTPS
  syncthing
  syncthing-gui

```

<u>Liste les profils disponibles:</u>

Profile Nginx Full: ouvre les ports 80 (http) et 443 (https)
Profile Nginx HTTP: ouvre les ports 80 (http)
Profile Nginx HTTPS: ouvre les ports 443 (https)



##### Activer le profile  Nginx Full:

```bash
$ sudo ufw allow 'Nginx Full'
Rule added
Rule added (v6)

```

##### Status du firewall:

```bash
$ sudo ufw status
Status: active

To                         Action      From

------

Nginx Full                 ALLOW       Anywhere                  
Nginx Full (v6)            ALLOW       Anywhere (v6)     

```



#### 