In this tutorial, we will go through:

  • Install and configure NGINX,
  • Install and configure SSL/TLS,
  • Configure NGINX as a reverse proxy for:
    • A whole site,
    • A directory of a site.

Requirements:

sudo apt update && sudo apt upgrade -y
sudo apt install nginx -y
sudo nano /etc/nginx/sites-available/default

Change the following configuration with your domain:

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    root /var/www/html;
    server_name example.com www.example.com;
}

Check the configuration and restart the server.

nginx -t && nginx -s reload

Access your website using your web browser and note that is labeled as an insecure connection.


SSL/TLS

Install the Cerbot and execute it against your :

sudo apt-get install certbot python3-certbot-nginx -y
sudo certbot --nginx

Only on the first time it will ass that many questions.

Alternatively, the domain could be specified to skip one step.

sudo certbot --nginx -d example.com -d example2.com

Reload the server and refresh the browser to verify that it was automatically redirected to a secure connection.

nginx -s reload

The browser will hop from HTTP://example.com to HTTPS://example.com.

Create a cron job using the root user to automatically renew the certificate that will expire every 90 days:

sudo su
crontab -e

Append:

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

REVERSE PROXY

To prevent CPU overload with multiple encrypted sessions it is recommended to use regular HTTP connection internally when possible (restricted VLAN for example).

Edit the virtual server configuration:

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

Applying the reverse proxy to the root of the website.

Edit the virtual server configuration:

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

Look for the location { … } block.

location / {
    proxy_pass http://127.0.0.1:5000;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

This configuration will forward the traffic to the host and port defined. The example above will forward to localhost under port 5000, which could be a docker application listening on this port.

All the lines in orange are optional and will provide metadata to the hidden application if necessary.

Applying the reverse proxy to a directory of the website.

Create a location block to the desired directory.

location /proxied_page/ {
    proxy_pass http://192.168.1.7;
}

In the example above the reverse proxy is applied only to the directory proxied_page to another host (192.168.1.7) in the private network on the default HTTP port.