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

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

How to install Nginx with Let's Encrypt on Ubuntu 18.04

After acquiring your desired domain name, you would need to connect it to a server.
Nginx is a modern and high-performance web server that also serves as a load balancer and reverse proxy. It is becoming a more preferable choice over Apache and can similarly work in conjunction with PHP, NodeJS, and other server-side languages to run your web stack.

Follow the guide below and run the commands one by one to configure your Ubuntu 18.04 server and install Nginx with Let’s Encrypt for free SSL certificates. You could enter your domain name below to automatically customize the commands and scripts according to web address.

Your domain name:

Login to your server via SSH (you might need to setup an SSH key if login via password is not allowed):

ssh root@your_server_ip

Create a new user (you should only log in as root for the initial setup and use this user for normal usage instead):

adduser webserver

Grant sudo privilege to your new user:

usermod -aG sudo webserver

Allow OpenSSH and enable the firewall:

ufw allow OpenSSH
ufw enable

Login to your server with the new user:

ssh webserver@your_server_ip

Update the source and install Nginx:

sudo apt update
sudo apt install nginx

Allow Nginx through the firewall:

sudo ufw allow 'Nginx Full'

Configure Nginx and add a server block for your domain name:

sudo mkdir -p /var/www/YOUR_DOMAIN_NAME/html
sudo chown -R $USER:$USER /var/www/YOUR_DOMAIN_NAME/html
sudo chmod -R 755 /var/www/YOUR_DOMAIN_NAME

Add an index page to be shown when visiting your website:

nano /var/www/YOUR_DOMAIN_NAME

Paste the following HTML code and save the file:

        <title>Welcome to YOUR_DOMAIN_NAME!</title>
        <h1>It works!</h1>

Create the Nginx config file:

sudo nano /etc/nginx/sites-available/YOUR_DOMAIN_NAME

Add the following server block and save the file:

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

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

        server_name YOUR_DOMAIN_NAME www.YOUR_DOMAIN_NAME;

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

Create a symlink to enable the nginx config:

sudo ln -s /etc/nginx/sites-available/YOUR_DOMAIN_NAME /etc/nginx/sites-enabled/

Edit the main nginx config file and uncomment the following line:

sudo nano /etc/nginx/nginx.conf
http {
    server_names_hash_bucket_size 64;

Restart nginx:

sudo systemctl restart nginx

Install Let’s Encrypt:

sudo add-apt-repository ppa:certbot/certbot
sudo apt install python-certbot-nginx
sudo certbot --nginx -d YOUR_DOMAIN_NAME -d www.YOUR_DOMAIN_NAME
sudo certbot renew --dry-run

Restart nginx:

sudo systemctl restart nginx

All done!