{{tag>tutoriel}} ====== LEMP - un serveur avec Linux, Nginx, MariaDB, PHP ====== **LEMP** ((**L**inux, NGINX (**e**ngine X), **M**ySQL/MariaDB, **P**HP/**P**erl/**P**ython)) est un serveur HTTP composé de : * **[[logiciel:reseau:web:serveur:nginx:start|]]** * **PHP**, ou plutôt le packet **php-fpm**, interface pour communiquer avec le serveur NGINX et PHP. * **[[logiciel:reseau:serveur:bdd:sql:mariadb:start|]]** * **[[logiciel:reseau:serveur:bdd:adminer:start|]]** ===== Pré-requis ===== **Pour le cas d'un Raspberry**, procéder en ligne de commande via SSH. * un **PC** sous Linux (ubuntu) (ou un Raspberry Pi accédé via **SSH**) * mis à jour :USER@MACHINE:~$ sudo apt update USER@MACHINE:~$ sudo apt upgrade USER@MACHINE:~$ sudo apt dist-upgrade ===== Première étape ===== - **Installez [[apt>nginx,php-fpm,php-gd,php-curl,php-intl,php-xmlrpc,php-mbstring,php-mysql,php-xml,php-zip]]** USER@MACHINE:~$ sudo apt install {nginx php-{fpm,gd,curl,intl,xmlrpc,mbstring,mysql,xml,zip}}Pour gérer les fichiers PHP avec Nginx, nous utilisons **php-fpm** (une version plus rapide de PHP) plutôt que PHP. Cette installation a créé le répertoire **/var/www/html** pour la racine des sites. - **Vérifiez que NGINX est bien démarré** : sur un PC du réseau, ouvrez dans un navigateur l'adresse IP du serveur [[http://]]. Si tout va bien, il s'affiche :{{ :tutoriel:reseau:web:serveur:lemp:lemp_001.png?400 |}}Vous pouvez aussi vérifier que le service NGINX est bien démarré :USER@MACHINE:~$ sudo systemctl is-active nginx active - **Sauvegardez les fichiers de configuration** :USER@MACHINE:~$ sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/default.dist ===== Autres étapes ===== - **[[tutoriel:reseau:web:serveur:racine:start|]]** - **Sauvegardez /etc/nginx/sites-available/default** :USER@MACHINE:~$ sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/default.dist - **Éditez avec les droits d'administration le fichier /etc/nginx/sites-available/default** : - **Remplacez la ligne**index index.html index.htm index.nginx-debian.html;parindex index.html index.htm index.php;Cela rajoute une redirection automatique vers les fichiers **index.php** pour les dossiers du site. - **Activez php-fpm** pour Nginx, modifiez les lignes #location ~ \.php$ { # include snippets/fastcgi-php.conf; # # # With php5-cgi alone: # fastcgi_pass 127.0.0.1:9000; # # With php5-fpm: # fastcgi_pass unix:/var/run/php/php7.0-fpm.sock; #}pour obtenir : location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php7.0-fpm.sock; } - **Modifiez les droits du dossier /var/www/html** pour gérer plus facilement les sites :USER@MACHINE:~$ sudo chown -R www-data:pi /var/www/html/ USER@MACHINE:~$ sudo chmod -R 2770 /var/www/html/ - **Ajoutez un fichier index.php** pour vérifier que PHP fonctionne :USER@MACHINE:~$ echo "" > /var/www/html/index.php - **Redémarrez Nginx** pour appliquer les modifications :USER@MACHINE:~$ sudo nginx -s reload - **Vérifiez l'installation de PHP** : - **Version de PHP installée** :USER@MACHINE:~$ php -v PHP 7.3.19-1~deb10u1 (cli) (built: Jul 5 2020 06:46:45) ( NTS ) ...-> Ici, la version de php installée est 7.3 - **État de PHP** :USER@MACHINE:~$ sudo systemctl status php7* ● php7.3-fpm.service - The PHP 7.3 FastCGI Process Manager ... Active: active (running) since Tue 2020-10-27 14:14:12 CET; 5min ago ... - **Sur un PC du réseau, ouvrez en http l'adresse IP du serveur** [[http://]]. Si tout va bien, une page affiche les informations de PHP. - **Installez [[logiciel:reseau:serveur:bdd:sql:mariadb:start|]]** - **Installez [[logiciel:reseau:transfert:serveur:vsftpd:start|]]** - **Installez [[logiciel:reseau:serveur:bdd:adminer:start|]]** - **Sécurisez Nginx** : * **[[tutoriel:reseau:web:serveur:nginx:ssl:autosigne:raspi:start|]]** * **[[tutoriel:reseau:web:serveur:nginx:ssl:letsencrypt:start|]]** ==== Désinstallation ==== - **Arrêtez nginx** :USER@MACHINE:~$ sudo systemctl stop nginx.service - **Démontez /var/www** et **/srv** :USER@MACHINE:~$ sudo umount /var/www USER@MACHINE:~$ sudo umount /srv - **Retirez (commentez) le montage de /var/www et /srv** :USER@MACHINE:~$ sudo nano /etc/fstab - **Supprimez php-fpm** :USER@MACHINE:~$ sudo apt purge php-fpm - **Supprimez nginx** :USER@MACHINE:~$ sudo apt purge nginx* - **Terminez l'effacement** :USER@MACHINE:~$ sudo apt autoremove - **Effacez /var/www/** et ses sous-répertoires :USER@MACHINE:~$ sudo rm -R /var/www/ ==== Installation du serveur MariaDB et du client en ligne de commande ==== - Installez [[apt>mariadb-server]]USER@MACHINE:~$ sudo apt install {mariadb-server,} - Vérifiez votre installation en lançant le client MariaDB en ligne de commande :USER@MACHINE:~$ sudo mariadb Welcome to the MariaDB monitor. Commands end with ; or \g. Your MariaDB connection id is 49 Server version: 10.3.25-MariaDB-0+deb10u1 Raspbian 10 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)]> exit ByeSortez de la session en tapant **exit**. C'est cet outil que vous utiliserez pour configurer l'instance de base de données pour votre application PHP. ==== Configuration par défaut de Nginx pour qu'il traite les requêtes PHP ==== - Faites une copie du fichier **/etc/nginx/sites-available/default** :USER@MACHINE:~$ sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/default.dist - Répérez le **socket d’écoute de php-fpm** :USER@MACHINE:~$ ls -l /var/run/php/ total 4 -rw-r--r-- 1 root root 5 oct. 27 08:15 php7.3-fpm.pid srw-rw---- 1 www-data www-data 0 oct. 27 08:15 php7.3-fpm.sock-> Ici, il faudra utiliser /var/run/php/php7.3-fpm.sock dans les fichiers de configuration de nginx. - **Éditez avec les droits d'administration le fichier etc/nginx/sites-available/default** pour le modifier comme ceci : - remplacez # Add index.php to the list if you are using PHP index index.html index.htm index.nginx-debian.html; par # Add index.php to the list if you are using PHP index index.html index.htm index.php index.nginx-debian.html; - remplacez # 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.3-fpm.sock; # # With php-cgi (or other tcp sockets): # fastcgi_pass 127.0.0.1:9000; #} par # 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.3-fpm.sock; } - Redémarrez Nginx USER@MACHINE:~$ sudo systemctl restart nginx - Pour vérifier que Nginx exécute PHP, créez le fichier **/var/www/html/index.php** : Dans votre navigateur, allez à [[http://]] :{{ :tutoriel:reseau:web:serveur:lemp:lemp_002.png?400 |}} ==== Configurer Nginx pour qu'il traite les requêtes PHP pour un nom de domaine ==== Supposons que nous souhaitons répondre aux requêtes PHP pour **abcd1234.com**. Créez avec les droits d'administration le fichier **/etc/nginx/sites-enabled/abcd1234.com.conf** : server { listen 80; ## Your website name goes here. server_name abcd1234.com www.abcd1234.com; root /var/www/abcd1234.com; ## This should be in your http block and if it is, it's not needed here. index index.php; location / { try_files $uri $uri/ /index.php?$args; } location ~ \.php$ { include fastcgi.conf; fastcgi_intercept_errors on; fastcgi_pass unix:/run/php/php7.3-fpm.sock; fastcgi_buffers 16 16k; fastcgi_buffer_size 32k; } } ==== Mise en place de PHP ==== - Éditez avec les droits d'administration le fichier **/etc/nginx/sites-available** pour y écrire ceci : # Site framboise4 server { listen 80; server_name framboise4.local; root /var/www/html; location / { index index.php index.html index.htm index.nginx-debian.html; try_files $uri $uri/ =404; } location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php7.3-fpm.sock; } location ~ /\.ht { deny all; } } server { listen 80; server_name ~^(?P.+)\.framboise4\.local$; root /var/www/html/$sub; location / { index index.php index.html index.htm index.nginx-debian.html; try_files $uri $uri/ =404; } location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php7.3-fpm.sock; } location ~ /\.ht { deny all; } } - **Installez les modules de php** (remplacez **php7.3** par la version trouvée ci-dessus) :USER@MACHINE:~$ sudo apt install php7.3-{fpm} - Pour les installer :USER@MACHINE:~$ sudo apt install php7.4-{fpm,cli,opcache,mbstring,curl,xml,gd,mysql,common,json,bcmath,bz2,intl,zip,pdo,imagick,tidy,xmlrpc,dev,imap,soap} FIXME php7.4-apc n'est pas retrouvé - **Installez [[logiciel:devlogiciel:php:start]]** - **[[logiciel:reseau:web:serveur:nginx:start|]]** - **Installez [[logiciel:reseau:web:serveur:nginx:raspi:start|]]** - **Installez la base de données SQL**, selon le cas : - **MariaDB** : définissez le mot de passe de l'utilisateur root de MariaDb :USER@MACHINE:~$ sudo mysql_secure_installationAu début, répondre Entrée car il n'y a pas de mot de passe, puis en donner un). MariaDB est installé et prêt à l'emploi. - **SQLite** : - Repérez la version de php installée :USER@MACHINE:~$ php -v PHP 7.4.3 (cli) (built: May 26 2020 12:24:22) ( NTS ) ... - et utilisez-la pour installer sqlite :USER@MACHINE:~$ sudo apt install sqlite sqlite-doc php7.4-sqlite3 ... Souhaitez-vous continuer ? [O/n] ... - Configurer MariaDB : vérifiez que MariaDb est bien démarré :USER@MACHINE:~$ sudo systemctl is-active nginx active ==== Démarrer le gestionnaire de processus FastCGI ==== - **Affichez la version de php** :USER@MACHINE:~$ php -v PHP 7.2.19-0ubuntu0.18.04.1 (cli) (built: Jun 4 2019 14:48:12) ( NTS ) Copyright (c) 1997-2018 The PHP Group Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies with Zend OPcache v7.2.19-0ubuntu0.18.04.1, Copyright (c) 1999-2018, by Zend Technologies - **Démarrez le gestionnaire de processus FastCGI** (aidez-vous de l'auto-complétion avec la version trouvée ci-dessus) :USER@MACHINE:~$ sudo systemctl enable php7.2-fpm Synchronizing state of php7.2-fpm.service with SysV service script with /lib/systemd/systemd-sysv-install. Executing: /lib/systemd/systemd-sysv-install enable php7.2-fpm PHP-FPM est une alternative à PHP FastCGI. ==== Configurer et démarrer le serveur NGINX ==== Une fois PHP installé, il faut indiquer à NGINX d'exécuter PHP en utilisant PHP-FPM. ++++ Fichier /etc/nginx/sites-available/default d'origine| ## # You should look at the following URL's in order to grasp a solid understanding # of Nginx configuration files in order to fully unleash the power of Nginx. # https://www.nginx.com/resources/wiki/start/ # https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/ # https://wiki.debian.org/Nginx/DirectoryStructure # # In most cases, administrators will remove this file from sites-enabled/ and # leave it as reference inside of sites-available where it will continue to be # updated by the nginx packaging team. # # This file will automatically load configuration files provided by other # applications, such as Drupal or Wordpress. These applications will be made # available underneath a path with that package name, such as /drupal8. # # Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples. ## # Default server configuration # 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 /var/www/html; # Add index.php to the list if you are using PHP index index.html index.htm index.nginx-debian.html; server_name _; 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:/var/run/php/php7.0-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; #} } # Virtual Host configuration for example.com # # You can move that to a different file under sites-available/ and symlink that # to sites-enabled/ to enable it. # #server { # listen 80; # listen [::]:80; # # server_name example.com; # # root /var/www/example.com; # index index.html; # # location / { # try_files $uri $uri/ =404; # } #} ++++ - **Dupliquez le fichier /etc/nginx/sites-available/default** :USER@MACHINE:~$ sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/default.dist - **Éditez avec les droits d'administration le fichier /etc/nginx/sites-available/default** pour le remplacer par ceci : server { listen 80 default_server; listen [::]:80 default_server; root /var/www/html; index index.php index.html index.htm index.nginx-debian.html; server_name _; location / { try_files $uri $uri/ =404; } location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php7.2-fpm.sock; } location ~ /\.ht { deny all; } } - Testez la configuration :USER@MACHINE:~$ sudo nginx -t nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successfulUSER@MACHINE:~$ sudo nginx -s stop USER@MACHINE:~$ sudo nginx - Créez un fichier /var/www/html/test/test.php dans le répertoire web racine de NGINX : - Vérification : [[http://localhost/test]] ==== Serveurs virtuels ==== Créez avec les droits d'administration le fichier **/etc/nginx/sites-available/monsite.tld** pour y écrire : server { listen 80; root /var/www/html; index index.php index.html index.htm index.nginx-debian.html; server_name monsite.tld; location / { try_files $uri $uri/ =404; } location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php7.2-fpm.sock; } location ~ /\.ht { deny all; } } **__Explications__** Voici ce que font ces directives et ces blocs location : - **listen** : Port sur lequel Nginx écoute. 80 = port par défaut pour HTTP - **root** : emplacement de la racine du site Web. - **index** : fichiers index.php prioritaires - **server_name** : nom de domaine ou adresse IP de votre serveur. - **location /** : La directive try_files vérifie l’existence de fichiers demandés. Si Nginx ne le trouve pas, il retourne une erreur 404. - **location ~ \.php$** : gère le traitement PHP en pointant Nginx vers le fichier de configuration fastcgi-php.conf et le fichier php7.2-fpm.sock, qui indique le type de socket associé à php-fpm.. - **location ~ /\.ht** : bloc location pour les fichiers .htaccess, que Nginx ne traite pas. La directive deny all ne transmet pas aux visiteurs des éventuels fichiers .htaccess Activez votre site en créant un lien symbolique dans le dossier **/etc/nginx/sites-enable** :USER@MACHINE:~$ sudo ln -s /etc/nginx/sites-available/monsite.tld /etc/nginx/sites-enabled/monsite.tld Redémarrez nginx :USER@MACHINE:~$ sudo nginx -s reload === Configuration d'hôtes virtuels sur NGinx avec support automatique des sous-domaines, du SSL et de l'authentification === === Configurer Nginx pour gérer automatiquement les sous-domaines locaux === - **Création d’un nouveau site nginx** : - **Éditez avec les droits d'administration le fichier /etc/nginx/sites-available/monsite.local** pour y écrire : server { # On écoute le port 80. listen 80; # expression régulière pour récupérer # le sous-domaine dans une variable nommée "sub". server_name ~^(?P.+)\.monsite\.local$; location / { # On définit le chemin local # en utilisant la variable "sub" récupérée précédemment. root /var/www/html/$sub; } } - **Activez votre site** en créant un lien symbolique dans le dossier **/etc/nginx/sites-enable** :USER@MACHINE:~$ sudo ln -s /etc/nginx/sites-available/local.dev /etc/nginx/sites-enable/monsite.local - **Redémarrez le serveur** :USER@MACHINE:~$ sudo service nginx restart - # Le nom du sous-domaine est mis dans une variable sub, # utilisée ensuite pour définir la racine # Sites dokuwiki server { listen 80; server_name ~^(?Pdoc|perso|site2)\.chateau\.parc$; root /var/www/html/$sub; location / { index index.php index.html index.htm; try_files $uri $uri/ =404; } location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php7.2-fpm.sock; } location ~ /(data|conf|bin|inc)/ { deny all; } location ~ /\.ht { deny all; } } # Autres sous-domaines server { listen 80; server_name ~^(?P.+)\.chateau\.parc$; root /var/www/html/$sub; location / { index index.php index.html index.htm index.nginx-debian.html; try_files $uri $uri/ =404; } location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php7.2-fpm.sock; } location ~ /\.ht { deny all; } } === Création des domaines génériques avec dnsmasq === - Installez [[apt>dnsmasq]]USER@MACHINE:~$ sudo apt install {dnsmasq,} - Éditez avec les droits d'administration le fichier **/etc/dnsmasq.d/local.conf** et ajoutez-lui la ligne : address=/mondomaine.tld/127.0.0.1 Dans notre exemple, nous avons donc ajouté : address=/monsite.local/127.0.0.1 - redémarrez dnsmasq :USER@MACHINE:~$ sudo systemctl restart dnsmasq : nos domaines sont accessibles. Désormais, tous les domaines ***.mondomaine.tld** existent. Vous pouvez le vérifier : - **Installez [[apt>dnsutils]]**USER@MACHINE:~$ sudo apt install {dnsutils,} - Lancez :USER@MACHINE:~$ dig test.localhost ; <<>> DiG 9.11.3-1ubuntu1.7-Ubuntu <<>> test.localhost ;; global options: +cmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 47480 ;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1 ;; OPT PSEUDOSECTION: ; EDNS: version: 0, flags:; udp: 65494 ;; QUESTION SECTION: ;test.localhost. IN A ;; ANSWER SECTION: test.localhost. 0 IN A 127.0.0.1 ;; Query time: 0 msec ;; SERVER: 127.0.0.53#53(127.0.0.53) ;; WHEN: Sat May 04 23:35:51 CEST 2019 ;; MSG SIZE rcvd: 59 ===== Conclusion ===== ===== Problèmes connus ===== ~~FAQ~~ ??? Erreur 403 forbidden, un classique de Nginx !!! L’erreur 403 est fréquente avec Nginx, mais simple à corriger. - Cela peut signifier que Nginx ne trouve pas de fichier à afficher. Pour tester cela, créez un fichier index.html dans le répertoire **/var/www** :echo 'Nginx marche !' > /var/www/html/index.html et ré-essayez d’accéder à votre site. Si le problème venait de là, vous devriez obtenir une page marquée **Nginx marche !** - Sinon, c'est peut-etre que Nginx ne peut accéder au répertoire **/var/www/html**. Dans ce cas, donne au répertoire **/var/www** les autorisations suffisantes. - Dernière possibilité : vous avez mal activé php. ===== Voir aussi ===== * **(fr)** [[https://web.developpez.com/tutoriels/creer-serveur-web-nginx-php-mariadb/|Créer un serveur Web Nginx + PHP7 + Maria DB (Mysql) + PhpMyAdmin sous Debian 9 Stretch]] * **(fr)** [[https://raspberry-pi.fr/installer-nginx-raspbian-raspberry/]] * **(en)** [[https://www.techcoil.com/blog/how-to-setup-a-raspberry-pi-lemp-server-with-raspbian-buster-lite-for-running-php-applications/|How to setup a Raspberry Pi LEMP server with Raspbian Buster Lite for running PHP applications]] * **(en)** [[https://www.digitalocean.com/community/tutorials/how-to-install-linux-nginx-mysql-php-lemp-stack-on-ubuntu-14-04]] ---- //Basé sur << [[https://web.developpez.com/tutoriels/creer-serveur-web-nginx-php-mariadb/|Créer un serveur Web Nginx + PHP7 + Maria DB (Mysql) + PhpMyAdmin sous Debian 9 Stretch]] >> par Quentin Beauvais.//