How to install Nginx with Let’s Encrypt on Ubuntu 20.04

In your terminal, enter the commands

sudo su
apt update
apt install nginx-full
ufw allow ssh
ufw allow 'Nginx Full'
ufw status
systemctl status nginx
mkdir -p /var/www/your-domain.com
nano /etc/nginx/sites-available/your-domain.com

Note: Please change your-domain.com with your actual domain name, add the below code and save the file.

server {
        listen 80;
        listen [::]:80;

        root /var/www/your-domain.com;
        index index.html index.htm;

        server_name your-domain.com www.your-domain.com;

        location / {
                try_files $uri $uri/ =404;
        }
}

Save the file by pressing Ctrl + o then press Enter key

Then press Ctrl + x to close the nano editor

After that, enable the site using the below command

ln -s /etc/nginx/sites-available/your-domain.com /etc/nginx/sites-enabled/

Then change hash bucket memory size using the below command

nano /etc/nginx/nginx.conf

Add server_names_hash_bucket_size 64; in http{ .. } bracket like below

http {
    server_names_hash_bucket_size 64;
}

Check Nginx file have any error or not using the below command

nginx -t

If the output is successful, then restart the Nginx server using the below command

systemctl restart nginx

Now add your project file to /var/www/your-domain.com folder

After that, Install Certbot and Nginx plugin using the below command

apt install certbot python3-certbot-nginx
sudo certbot --nginx -d your-domain.com -d www.your-domain.com

After that, follow the process of Certbot then showing success message like below

Congratulations! Your certificate and chain have been saved at:
....
....

After that, verify auto-renewal using the below command

systemctl status certbot.timer
certbot renew --dry-run

If you want to add a cron job for auto-renewal, you can use the below process

crontab -e

Add the below line and save the file

0 12 * * * /usr/bin/certbot renew --quiet

Leave a Reply