How to Install SSL Certificate for Nginx on Ubuntu Server 20.04

Louis SanchezJuly 29th 2021, 7:34

Follow these steps to set HTTPs on Nginx

Generating SSL Certificates

Step 1 : Create a directory to hold all certificate and keys

sudo mkdir -p /etc/nginx/ssl/example.com

Step 2 : Change to the new directory and enter the following command to create a certificate and SSL key

cd /etc/nginx/ssl/example.com
sudo openssl req -newkey rsa:2048 -x509 -nodes -days 365 -keyout example.com.key -out example.com.crt

Step 3 : This will prompt you to enter some information about your company and website.

Step 4 : After you are done with it, you can check the generated certificate and key

ls -l

Configuring Nginx

Step 5 : Create a virtual host entry or edit it if you already have one:

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/html;
    index index.php index.html index.htm;

    ssl_certificate     /etc/nginx/ssl/example.com/example.com.crt;
    ssl_certificate_key     /etc/nginx/ssl/example.com/example.com.key;
    # if you have received ca-certs.pem from Certification Authority
    #ssl_trusted_certificate /etc/nginx/ssl/example.com/ca-certs.pem;


    location / {
        try_files $uri $uri/ /index.php;
    }

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; 
    }
}

Step 6 : Enable this configuration by creating a symbolic link to it under sites-enabled

sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/example.com

Step 7 : Check the configuration for syntax errors

sudo nginx -t

Step 8 : Reload Nginx for the changes to take effect

sudo service nginx reload

Step 9 : Now, open your browser on the client system and point it to your domain name or IP address with HTTPS at the start:

https://example.com

Step 10 : Your browser may return an error saying Invalid Certification Authority. This is fine as we are using a self-signed certificate.