Setting up SSL in Nginx Web Server

Create Self-signed certificate

The first step is to generate your self-signed certificate. To do this, log into your server and issue the following command:

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

PLEASE adjust the days to your needs.

Configuration of NGINX for SSL

Now we need to configure NGINX to use SSL. First, create a new configuration snippet file with the command:

sudo vim /etc/nginx/snippets/self-signed.conf

In that new file, add the following contents:

ssl_certificate /etc/ssl/certs/nginx-selfsigned.crt;
ssl_certificate_key /etc/ssl/private/nginx-selfsigned.key;

Save and close that file.
Next, create a second configuration snippet that points to our newly-generated SSL key and certificate. To do this, issue the command:

sudo vim /etc/nginx/snippets/ssl-params.conf

In that new file, add the following contents:

ssl_protocols TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_dhparam /etc/ssl/certs/dhparam.pem;
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 valid=300s;
resolver_timeout 5s;
add_header X-Frame-Options DENY;
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";

Because here we are using a self-signed certificate, we disable SSL stapling (a method for quickly and safely determining whether or not an SSL certificate is valid). If you're not using a self-signed certificate, remove the # symbols before the two lines. You can also change the resolver line to reflect your preferred DNS servers. Save and close that file.
We also need to generate the dhparam.pem file with the command:

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

Hint: This command will take some time.

The next step is to configure NGINX to be aware that we're going to be using SSL. Let's assume you have a server block for in sites-available. Open that server block with the command:

sudo vim /etc/nginx/sites-available/

In that file, edit it to reflect the following:

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    include snippets/self-signed.conf;
    include snippets/ssl-params.conf;


    root /var/www/html;
    index index.html index.htm index.nginx-debian.html;