HTTPS Setup for Nginx web server

This is a short step-by-step recipe for setup of secure HTTPS connections for Nginx web server, using the free "Let's Encrypt" service. This recipe is used in courses IDATA2301 Web technologies and IDATA2306 Application Development at NTNU, campus Aalesund.

This recipe is based on the guide "Using Free Let’s Encrypt SSL/TLS Certificates with NGINX".

Before you begin - you should get a domain name for your server. This step is optional, but recommended. Alternatively, you can use HTTPS for an IP address, but that is not conventional. Domain registration is not described here.

Instructions:

  1. Log into your server using SSH
  2. Install Certbot command-line tool, provided by Let's Encrypt. To do that, run the following commands:
        sudo apt update
        sudo apt install certbot python3-certbot-nginx
            
  3. Let Nginx know which domain you are using - edit the config file: sudo nano /etc/nginx/sites-enabled/default. There you specify line server_name yourDomain; For example, if the domain is example.com, then the file looks as follows: Nginx configuration file with server name marked
  4. Restart the Nginx web server: sudo /etc/init.d/nginx restart
  5. Run CertBot to obtain certificate for your domain (replace example.com with your domain!)
    sudo certbot --nginx -d example.com
  6. Answer the questions asked. Suggested: redirect all traffic to HTTPS.
  7. If you take a look in the config file, you see that Certbot has added the necessary config lines. It has also saved the .pem file with the certificate, including the private key. Keep it secret! See the lines added by Certbot marked in the picture below. Nginx config file with some lines added by Certbot
  8. To set up automatic certificate renewal, add the following line to cron tasks (command to edit cron tasks: sudo crontab -e):
    0 12 * * * /usr/bin/certbot renew --quiet

That's all, Folks!