====== Serveur web Apache httpd 2.4, php7.0, MariaDB, et HTTPS par Let's Encrypt ======
===== Information =====
Au 17/10/2017 : Debian 9, Apache 2.4.25, PHP-FPM 7.0.19, MariaDB 10.1.23, OpenSSL 1.1.0f.
Testé sur Debian 9. Cet article implique d'avoir déjà des connaissances sur les éléments utilisés, car tout n'est pas détaillé. Le score sur [[https://www.ssllabs.com/ssltest|SSLLABS]] est A+.
Cette page indique l'installation de [[linux:fail2ban-apache-antibot|fail2ban, voir cette page du wiki pour le configurer]].
===== Installation des packages =====
Installation de Apache2, PHP7.0-FPM, MariaDB
apt install apache2 php7.0-fpm php7.0 php7.0-sqlite php7.0-mysql php7.0-gd php7.0-curl php7.0-xml php7.0-zip php7.0-mbstring php7.0-apcu mariadb-server openssl fail2ban
Activation de modules apache2
a2enmod rewrite #pour réécriture d'url
a2enmod ssl #pour SSL
a2enmod headers #pour entêtes SSL
a2enmod expires #pour le cache
a2enmod proxy #pour php7.0-fpm
a2enmod proxy_fcgi #pour php7.0-fpm
===== Configuration de MariaDB =====
La commande suivante est recommandée en environnement de production. Elle permet de sécuriser un minimum l'installation de MariaDB.
mysql_secure_installation
===== Configuration php7.0-fpm =====
Editer le fichier php.ini
nano /etc/php/7.0/fpm/php.ini
Et ajouter/modifier les infos suivantes :
post_max_size = 20M
upload_max_filesize = 20M
max_execution_time = 60
memory_limit = 128M
Configurer le cache OpCode pour php7.0-fpm :
nano /etc/php/7.0/mods-available/opcache.ini
Ajouter/modifier :
; configuration for php ZendOpcache module
; priority=05
zend_extension=opcache.so
opcache.memory_consumption = 256
opcache.interned_strings_buffer = 16
opcache.max_accelerated_files = 4000
opcache.revalidate_freq = 10
opcache.fast_shutdown=1
Il est possible de surveiller l'utilisation du cache avec [[https://github.com/rlerdorf/opcache-status|opcache.php disponible sur github]].
Si les sites hébergés sont à faible ou moyenne fréquentation, on peut optimiser php7.0-fpm en passant le nombre de process géré à la demande.
Editer le fichier :
nano /etc/php/7.0/fpm/pool.d/www.conf
Ajouter/modifier :
pm = ondemand
pm.max_children = 20
pm.process_idle_timeout = 10s
pm.max_requests = 500
Redémarrer php7.0-fpm pour charger la nouvelle configuration :
service php7.0-fpm restart
Il est possible de faire cohabiter php7.0-fpm avec d'autres versions.
===== Configuration apache2 =====
Désactiver php7.0 pour mpm_prefork :
a2dismod php7.0
Activer php7.0-fpm :
a2enconf php7.0-fpm
Attention, cette configuration sera globale à tout vos vhosts !
Alternativement, on peux ajouter php7.0-fpm directement au fichier vhost avec le code suivant :
##### PHP7.0-FPM #####
# Enable http authorization headers
SetEnvIfNoCase ^Authorization$ "(.+)" HTTP_AUTHORIZATION=$1
SetHandler "proxy:unix:/run/php/php7.0-fpm.sock|fcgi://localhost"
# Deny access to raw php sources by default
# To re-enable it's recommended to enable access to the files
# only in specific virtual host or directory
Require all denied
# Deny access to files without filename (e.g. '.php')
Require all denied
On peut alors le mettre dans la section , s'appliquant ainsi seulement au domaine désiré. On peut donc faire cohabiter plusieurs versions de php en mode fpm, en fonction des besoins pour chaque domaine.
Passage en mpm_worker pour apache2 :
apachectl -V | grep -i mpm
a2dismod mpm_prefork
a2enmod mpm_worker
service apache2 restart
apachectl -V | grep -i mpm
Désactiver le fichier de configuration par défaut d'apache :
a2dissite 000-default
service apache2 reload
===== Exemple de fichier vhost =====
Cet exemple de vhost est pour apache 2.4 en HTTP ! Voir La section sur Let's Encrypt pour HTTPS.
############################################################
# domain.info #
############################################################
##### HTTP
ServerName www.domain.info
ServerAlias www.domain.info domain.info
DocumentRoot "/home/www-data/domain.info/www"
#Redirection automatique vers HTTPS
#Redirect "/" "https://www.domain.info/"
CustomLog /home/www-data/logs/apache2/www.domain.info-access.log combined
ErrorLog /home/www-data/logs/apache2/www.domain.info-error.log
AccessFileName .htaccess
DirectoryIndex index.php index.html
Options FollowSymLinks
AllowOverride All
Order Deny,Allow
Require all granted
On peut changer ''Require all granted'' par ''Require ip x.x.x.x'' pour une interface d'administration privée, par exemple. Seule l'IP client indiquée pourra charger les pages, les autres auront une erreur 403.
La ligne commentée ''Redirect'' forcera l'utilisation de HTTPS. La décommenter quand HTTPS sera configuré et son fonctionnement validé.
Copier ou rendre le vhost disponible dans ''/etc/apache2/sites-available/www.domain.info.conf''. Ici on fait un lien symbolique :
ln -s /home/www-data/domain.info/www.domain.info.conf /etc/apache2/sites-available/www.domain.info.conf
Donnez les bons droits sur le fichier de configuration pour Apache 2 :
chown www-data:www-data /home/www-data/domain.info/www.domain.info.conf
Puis activer cette configuration :
a2ensite www.domain.info
Le domaine doit être accessible par http. Https n'est pas disponible sans la génération de certificat par Let's Encrypt et CertBot (gratuit) ou un autre fournisseur tier.
===== Let's Encrypt et CertBot =====
Cette partie concerne l'ajout d'un certificat pour SSL pour passer en HTTPS.
Commencer par récupérer CertBot dans un dossier.
wget https://dl.eff.org/certbot-auto
chmod a+x certbot-auto
./certbot-auto
Les dépendances vont s'installer.
Puis générer les certificats, sans auto-configuration d'apache par CertBot (on le fais manuellement dans le vhost).
./certbot-auto certonly --webroot -w /home/www-data/domain.info/www -d domain.info
Le paramètre ''-w'' indique une racine web et ''-d'' le domaine associé. On peut spécifier plusieurs ''-d'' après ''-w''. On peux recommencer cet enchaînement pour plusieurs racines web, dans la même commande.
Pour renouveler les certificats :
./certbot-auto renew
Pour automatiser, mettre la commande en tâche cron.
Pensez à modifier le fichier virtualhost pour pointer vers ''cert.pem'', ''privkey.pem'' et ''chain.pem'' (ou fichiers équivalents).
Modifier le fichier de configuration ssl d'apache :
nano /etc/apache2/mods-available/ssl.conf
Modifier/ajouter pour obtenir ces paramètres :
SSLCipherSuite "AES256+EECDH:AES256+EDH:AES128+EECDH:AES128+EDH"
SSLHonorCipherOrder on
SSLProtocol all -SSLv3 -SSLv2
SSLStrictSNIVHostCheck Off
SSLCompression Off
SSLUseStapling On
SSLStaplingCache "shmcb:${APACHE_RUN_DIR}/stapling_cache(128000)"
Ajoutez ensuite les informations au VirtualHost de votre site pour HTTPS :
##### HTTPS
ServerName www.domain.info
ServerAlias www.domain.info domain.info
DocumentRoot "/home/www-data/domain.info/www"
#Rewrite pour forcer "www"
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www.domain.info [NC]
RewriteRule ^(.*)$ https://www.domain.info$1 [L,R=301]
CustomLog /home/www-data/logs/apache2/www.domain.info-ssl-access.log combined
ErrorLog /home/www-data/logs/apache2/www.domain.info-ssl-error.log
AccessFileName .htaccess
DirectoryIndex index.php index.html
Options FollowSymLinks
AllowOverride All
Order Deny,Allow
Require all granted
SSLEngine on
SSLCertificateFile "/etc/letsencrypt/live/domain.info/cert.pem"
SSLCertificateKeyFile "/etc/letsencrypt/live/domain.info/privkey.pem"
SSLCertificateChainFile "/etc/letsencrypt/live/domain.info//chain.pem"
Header always set Strict-Transport-Security "max-age=31556926; preload"
Appliquez tout vos changements en redémarrant le service apache2 :
service apache2 restart
===== Logrotate sur vos logs apache2 custom =====
Créer le fichier ''/etc/logrotate.d/www-data-rotate''
/home/www-data/logs/apache2/*.log {
daily
missingok
rotate 30
notifempty
create 640 root
sharedscripts
postrotate
if /etc/init.d/apache2 status > /dev/null ; then \
/etc/init.d/apache2 reload > /dev/null; \
fi;
endscript
prerotate
if [ -d /etc/logrotate.d/www-data-prerotate ]; then \
run-parts /etc/logrotate.d/www-data-prerotate; \
fi; \
endscript
}
On peut aussi ajouter les éléments ''compress'' (compresse les anciens logs) et ''delaycompress'' (ne compresse pas l'avant dernier fichier de logs). Ne les ajoutez pas si vos logs sont surveillés par fail2ban.
===== Sources =====
[[https://certbot.eff.org/#debianwheezy-apache|certbot.eff.org]] - [[https://gist.github.com/hroling/85f36e86d48285f08161|github.com/hroling]] - [[http://morknet.de/smork/entry/wie-man-ein-a-rating-bei-ssllabs-erhaelt/|morknet.de]] - [[https://www.ssllabs.com|ssllabs.com]] - [[https://www.howtoforge.com/using-php5-fpm-with-apache2-on-ubuntu-12.04-lts|howtoforge.com]] - [[https://www.digitalocean.com/community/questions/apache-2-4-with-php5-fpm|digitalocean.com]] - [[https://www.digitalocean.com/community/tutorials/how-to-optimize-apache-web-server-performance|digitalocean.com]] - [[https://wiki.apache.org/httpd/PHP-FPM|wiki.apache.org]] - [[http://askubuntu.com/questions/524770/apache-enable-worker-mpm/525035|askubuntu.com]] - [[https://ma.ttias.be/apache-2-4-proxypass-for-php-taking-precedence-over-filesfilesmatch-in-htaccess/|ma.ttias.be]] - [[http://serverfault.com/questions/439692/apache-and-multiple-php-fpm-pools|serverfault.com]] - [[https://www.guillaume-leduc.fr/une-autre-facon-dutiliser-php-fpm.html|guillaume-leduc.fr]] - [[https://www.croc-informatique.fr/2009/06/rotation-des-logs-avec-logrotate/|croc-informatique.fr]] - [[https://www.abyssproject.net/2017/06/monter-serveur-web-debian-9/|abyssproject.net]]