Setting up nginx + certbot

Desired domain

Nginx

Install and enable nginx

sudo apt install nginx
sudo systemctl enable nginx

Adjust firewall

sudo ufw app list
sudo ufw allow 'Nginx HTTP'
sudo ufw allow 'OpenSSH'
sudo ufw allow ssh
sudo ufw enable
sudo ufw status

Check web server

systemctl status nginx

Should output active status

curl -4 icanhazip.com

Open this IP in browser to checn Nginx default page

Setting Up Server Blocks

sudo mkdir -p /var/www/your_domain/html
sudo chown -R $USER:$USER /var/www/your_domain/html
sudo chmod -R 755 /var/www/your_domain
nano /var/www/your_domain/html/index.html
<html>
  <head>
    <title>Welcome to your_domain!</title>
  </head>
  <body>
    <h1>Success! The your_domain server block is working!</h1>
  </body>
</html>
sudo nano /etc/nginx/sites-available/your_domain
server {
  listen 80;
  listen [::]:80;

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

  server_name your_domain www.your_domain;

  location / {
    try_files $uri $uri/ =404;
  }
}
sudo ln -s /etc/nginx/sites-available/your_domain /etc/nginx/sites-enabled/
sudo nano /etc/nginx/nginx.conf

Find and uncomment server_names_hash_bucket_size

sudo nginx -t
sudo systemctl restart nginx

Certbot

Install certbot

sudo snap install core; sudo snap refresh core
sudo apt remove certbot
sudo snap install --classic certbot
sudo ln -s /snap/bin/certbot /usr/bin/certbot

Reconfigure ufw

sudo ufw allow 'Nginx Full'
sudo ufw delete allow 'Nginx HTTP'

Obtaining an SSL Certificate

sudo certbot --nginx -d your_domain -d www.your_domain

Verifying Certbot Auto-Renewal

sudo systemctl status snap.certbot.renew.service
sudo certbot renew --dry-run

Update nginx config

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

Replace ONLY location section

server {
  listen 443 ssl http2;
  # Remove '#' in the next line to enable IPv6
  # listen [::]:443 ssl http2;
  server_name {name};
  ssl_certificate     /etc/letsencrypt/live/{name}/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/{name}/privkey.pem;

  ### copy from here
  location / {
    proxy_set_header   X-Real-IP $remote_addr;
    proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header   Host $host;
    proxy_pass         http://localhost:3001/;
    proxy_http_version 1.1;
    proxy_set_header   Upgrade $http_upgrade;
    proxy_set_header   Connection "upgrade";
  }
  ### to here
}

Check nginx config and restart nginx

sudo nginx -t
sudo systemctl restart nginx