In this recipe, we will learn how to enable HTTPs communication on the Nginx server.
Follow these steps to set HTTPs on Nginx:
$ sudo mkdir -p /etc/nginx/ssl/example.com
$ sudo nano /etc/nginx/sites-available/example.com
server { listen 80; server_name example.com www.example.com; return 301 https://$host$request_uri; } server { listen 443 ssl; server_name example.com www.example.com; root /var/www/example.com/public_html; index index.php index.html index.htm; ssl on; ssl_certificate /etc/nginx/ssl/example.com/server.crt; ssl_certificate_key /etc/nginx/ssl/example.com/server.key; # if you have received ca-certs.pem from Certification Authority #ssl_trusted_certificate /etc/nginx/ssl/example.com/ca-certs.pem; ssl_session_cache shared:SSL:10m; ssl_session_timeout 5m; keepalive_timeout 70; ssl_ciphers "HIGH:!aNULL:!MD5 or HIGH:!aNULL:!MD5:!3DES"; ssl_prefer_server_ciphers on; ssl_protocols TLSv1.2 TLSv1.1 TLSv1; add_header Strict-Transport-Security "max-age=31536000"; location / { try_files $uri $uri/ /index.php; } location ~ .php$ { include fastcgi_params; fastcgi_pass unix:/var/run/php/php7.0-fpm.sock; } }
sites-enabled
:$ sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/example.com
$ sudo nginx -t
$ sudo service nginx reload
When you know some basic configuration parameters, Nginx is quite simple to set up. Here, we have taken a few SSL settings from the default configuration file and added a simple redirection rule to redirect non-HTTPs traffic on port 80
to port 443
. The first server
block takes care of the redirection.
In addition to specifying the server certificate and keys, we have enabled session resumption by setting the cache to be shared across the Nginx process. We also have a timeout value of 5
minutes.
All other settings are common to the Nginx setup. We have allowed the virtual host to match with example.com
, as well as www.example.com
. We have set the index to search index.php
, followed by index.html
and others. With location
directives, we have set Nginx to search for files and directories before forwarding the request to a PHP processor. Note that if you create a self-signed certificate, you will notice your browser complaining about invalid certification authority.