How to secure your Nginx website with SSL using Let’s Encrypt on Ubuntu 18.04

July 12, 2020

Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free TLS/SSL certificates for enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client,Certbot, that attempts to automate most of the required steps for both Apache and Nginx.

Install certbot

sudo add-apt-repository ppa:certbot/certbot
sudo apt update
sudo apt-get install certbot
sudo apt-get install python-certbot-nginx
certbot --version

Obtain an SSL certificate

You should already a website configuration for your domain in nginx at/etc/nginx/sites-available/

server {

Then obtain an SSL certificate and get certbort do all the configuration by itself for Nginx:

$ sudo certbot --nginx -d -d

You can choose to auto redirect HTTP request to HTTPS during this command execution.

You can double check your nginx website configuration after this command/etc/nginx/sites-available/

server {
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/; 
    ssl_certificate_key /etc/letsencrypt/live/;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; 
server {
    if ($host = {
        return 301 https://$host$request_uri;
    } # managed by Certbot
    listen 80;
    return 404; # managed by Certbot

Then restart your nginx and enjoy your secured HTTPS website:

$ sudo nginx -t
$ sudo service nginx reload

Auto renew Let’s Encrypt’s certificate

Let’s Encrypt’s certificates are only valid for ninety days. This is to encourage users to automate their certificate renewal process. Thecertbotpackage we installed takes care of this for us by adding a renew script to/etc/cron.d. This script runs twice a day and will automatically renew any certificate that’s within thirty days of expiration.

You can see this cronjob in/etc/cron.d/certbotfile:

0 */12 * * * root test -x /usr/bin/certbot -a \! -d /run/systemd/system && perl -e 'sleep int(rand(43200))' && certbot -q renew

To test the renewal process, you can do a dry run withcertbot:

sudo certbot renew - dry-run

If you see no errors, you’re all set. Enjoy your secured website!

Written by Manoj Bhardwaj who lives and works in Mohali Punjab (India). My stackoverflow