Aller au contenu

nginx

SSL

Création d'un certificat ssl self-signed:

sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/ssl/private/nginx-selfsigned.key -out /etc/ssl/certs/nginx-selfsigned.crt
# => /etc/ssl/certs/nginx-selfsigned.crt

sudo openssl dhparam -out /etc/ssl/certs/dhparam.pem 2048
# => /etc/ssl/certs/dhparam.pem 

sudo nano /etc/nginx/snippets/self-signed.conf
# ajouter:
ssl_certificate /etc/ssl/certs/nginx-selfsigned.crt;
ssl_certificate_key /etc/ssl/private/nginx-selfsigned.key;

sudo nano /etc/nginx/snippets/ssl-params.conf
# ajouter:
# from https://cipherli.st/
# and https://raymii.org/s/tutorials/Strong_SSL_Security_On_nginx.html

ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH";
ssl_ecdh_curve secp384r1;
ssl_session_cache shared:SSL:10m;
ssl_session_tickets off;
ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 5s;
# Disable preloading HSTS for now.  You can use the commented out header line that includes
# the "preload" directive if you understand the implications.
#add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload";
add_header Strict-Transport-Security "max-age=63072000; includeSubdomains";
add_header X-Frame-Options DENY;
add_header X-Content-Type-Options nosniff;

ssl_dhparam /etc/ssl/certs/dhparam.pem;

Configurer nginx pour qu'il utilise SSL:

sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/default.bak
sudo nano /etc/nginx/sites-available/default
# 1. Redirection http vers https
# /etc/nginx/sites-available/default

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    root /var/www/debian/html;

    index index.html index.htm index.php index.nginx-debian.html;

    server_name localhost;
    # redirection temporaire (302), permanente (301)
    return 302 https://$server_name$request_uri;

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

server {
    # SSL configuration

    listen 443 ssl http2 default_server;
    listen [::]:443 ssl http2 default_server;
    include snippets/self-signed.conf;
    include snippets/ssl-params.conf;
}
# 2. Autoriser http et https
# /etc/nginx/sites-available/default

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    listen 443 ssl http2 default_server;
    listen [::]:443 ssl http2 default_server;

    root /var/www/debian/html;

    index index.html index.htm index.php index.nginx-debian.html;

    server_name localhost;
    return 302 https://$server_name$request_uri;

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

    include snippets/self-signed.conf;
    include snippets/ssl-params.conf;
}

Tester la configuration:

# message normal pour certificat auto-signé

sudo /usr/sbin/nginx -t
nginx: [warn] "ssl_stapling" ignored, issuer certificate not found for certificate "/etc/ssl/certs/nginx-selfsigned.crt"
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is success

Et redémarrer nginx:

sudo systemctl restart nginx

Vérifier le status de nginx:

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 Tue 2021-07-13 09:30:48 CEST; 2min 58s ago
     Docs: man:nginx(8)
  Process: 14769 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, sta
  Process: 14770 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUC
 Main PID: 14771 (nginx)
    Tasks: 5 (limit: 4682)
   Memory: 5.7M
   CGroup: /system.slice/nginx.service
           ├─14771 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
           ├─14772 nginx: worker process
           ├─14773 nginx: worker process
           ├─14774 nginx: worker process
           └─14775 nginx: worker process

Logs

/var/log/nginx$ ls -la
-rw-r-----  1 www-data adm  2812 juil. 13 12:00 access.log
-rw-r-----  1 www-data adm  3252 juil. 13 11:51 error.log
nano /etc/nginx/nginx.conf 

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

Utilisation

On commande nginx avec SystemD (Debian 8+, ubuntu 16+, CentOS):

Arrêter nginx
systemctl stop nginx.service
Démarrer nginx
systemctl start nginx.service
Redémarrer nginx
systemctl restart nginx
Recharger nginx
systemctl reload nginx
Désactiver nginx
systemctl disable nginx
Activer nginx
systemctl enable nginx

On peut controller directement nginx avec les signals:

Relancer nginx
sudo /usr/sbin/nginx -s reload

Aide:

sudo /usr/sbin/nginx -h
nginx version: nginx/1.14.2
Usage: nginx [-?hvVtTq] [-s signal] [-c filename] [-p prefix] [-g directives]

Options:
  -?,-h         : this help
  -v            : show version and exit
  -V            : show version and configure options then exit
  -t            : test configuration and exit
  -T            : test configuration, dump it and exit
  -q            : suppress non-error messages during configuration testing
  -s signal     : send signal to a master process: stop, quit, reopen, reload
  -p prefix     : set prefix path (default: /usr/share/nginx/)
  -c filename   : set configuration file (default: /etc/nginx/nginx.conf)
  -g directives : set global directives out of configuration file

Tester la configuration:

sudo /usr/sbin/nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Tester la configuration et l'afficher:

sudo /usr/sbin/nginx -T
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
# configuration file /etc/nginx/nginx.conf:
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 768;
    # multi_accept on;
}

http {
    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

.../...
}

# configuration file /etc/nginx/modules-enabled/50-mod-http-auth-pam.conf:
load_module modules/ngx_http_auth_pam_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-http-dav-ext.conf:
load_module modules/ngx_http_dav_ext_module.so;

.../...

# configuration file /etc/nginx/mime.types:

types {
    text/html                             html htm shtml;
    text/css                              css;
        .../...
}

# configuration file /etc/nginx/sites-enabled/default:
##
# 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;

  .../...

  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:/run/php/php7.3-fpm.sock;
    #   # With php-cgi (or other tcp sockets):
    #   fastcgi_pass 127.0.0.1:9000;
    #}

}


# 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;
#   }
#}
http {

    server {
        listen 80;
        server_name localhost;

            location / {
            root /var/service/web;
            index index.html index.htm index.php;
        }

            error_page 500 502 503 504  /50x.html;
            location = /50x.html {
            root /usr/share/nginx/html; 
        }

        access_log /var/log/nginx/myexample.access.http.log;
        error_log /var/log/nginx/myexample.error.http.log;
    }

    server {
        listen 443;
        server_name localhost;

            location / {
            root /var/service/web;
            index index.html index.htm index.php;
        }

            error_page 500 502 503 504  /50x.html;
            location = /50x.html {
            root /usr/share/nginx/html; 
        }

        access_log /var/log/nginx/myexample.access.https.log;
        error_log /var/log/nginx/myexample.error.https.log;

        ssl on;
        ssl_certificate /etc/nginx/ssl/server.crt;
        ssl_certificate_key /etc/nginx/ssl/server.key;    
    }

}

Site accessible via HTTP et HTTPS:

server {
        listen 80;
        root /var/www/html;
        index index.html index.htm index.php;
        server_name example.com example;
        access_log /var/log/nginx/myexample.access.http.log;
        error_log /var/log/nginx/myexample.error.http.log;
}

server {
        listen 443;
        root /var/www/html;
        index index.html index.htm index.php;
        server_name example.com example;
        access_log /var/log/nginx/myexample.access.https.log;
        error_log /var/log/nginx/myexample.error.https.log;
        ssl on;
        ssl_certificate /etc/nginx/ssl/server.crt;
        ssl_certificate_key /etc/nginx/ssl/server.key;
}

Reverse proxy:

upstream mysite {
         server localhost:8080;
}
server {
         server_name mysite.local;
         location / {
              proxy_pass http://mysite.local;
              }
}

PHP:

location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
}

Redirige les www. vers la version sans www

server {
    listen 80;
    server_name www.monsupersite.fr;
    return 301 http://monsupersite.fr$request_uri;
}

Dernière mise à jour: March 4, 2022