How to Configure a Nginx HTTPs Reverse Proxy on Ubuntu Server 20.04

Louis SanchezAugust 15th 2021, 2:14

We will use Nginx as a reverse proxy, which will serve all static content and pass the requests for dynamic content to Apache.

Follow these steps to set Nginx as a reverse proxy:

Step 1 : Install Nginx with the following command

sudo apt-get update
sudo apt-get install nginx

Step 2 : Create a new site configuration under /etc/nginx/sites-available and add the following content to it:

sudo nano /etc/nginx/sites-available/reverse_proxy
server {
    listen 80;

    root /var/www/example.com/html;
  
    index index.php index.html index.htm;

    server_name example.com;

    location / {
        try_files $uri $uri/ /index.php;
    }

    location ~ \.php$ {
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header Host $host;
        proxy_pass http://127.0.0.1:8080;
    }
    location ~* \.(js|css|jpg|jpeg|png|svg|html|htm)$ {
        expires      30d;
    }

    location ~ /\.ht {
        deny all;
    }
}

Step 3 : Enable this new configuration by creating a symbolic link under sites-enabled

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

Step 4 : Install Apache

sudo apt-get install apache2

Step 5 : We need to change the Apache settings to listen on port 8080. This will leave port 80 to be used by Nginx

sudo nano /etc/apache2/ports.conf
Listen 127.0.0.1:8080

Step 6 : Also change NameVirtualHost, if you are using it

NameVirtualHost 127.0.0.1:8080

Step 7 : Create the virtual hosts settings to listen on port 8080

sudo nano /etc/apache2/sites-available/example.com.conf
<VirtualHost 127.0.0.1:8080>
    ServerName example.com
    ServerAdmin webmaster@example.com
    DocumentRoot /var/www/example.com/html
</VirtualHost>

Step 8 : Enable our new VirtualHost with a2ensite and reload Apache:

cd /etc/apache2/sites-available/
sudo a2ensite example.com.conf

Step 9 : Create a index.php
mkdir -p /var/www/example.com/html
sudo chown $USER:www-data -R /var/www/example.com
sudo chmod 775 -R /var/www/example.com
echo '<h1>Hello World</h1>' > /var/www/example.com/html/index.php

Step 10 : Save the changes and restart Apache, Nginx for the changes to take effect:

sudo service apache2 restart
sudo service nginx restart

Step 11 : Check for open ports with the following command

sudo netstat -pltn

Step 12 : Open your browser and point it to the IP address of your server.