Table of Contents

Web Servers - Nginx - Setup Nginx Reverse Proxy

A Reverse Proxy sits between a client and a web server (or servers) and acts as a frontend by handling all incoming client requests and distributing them to the backend web, database, and/or other server(s).

Other benefits of a Reverse Proxy include:


Install NginX

sudo apt install nginx

Disable the default virtual host

unlink /etc/nginx/sites-enabled/default

Create a reverse proxy configuration file

All of the settings for the reverse proxy will go inside of a configuration file, and this file needs be placed inside the sites-available directory.

cd /etc/nginx/sites-available

Create the configuration file: /etc/nginx/sites-available/reverse-proxy.conf

/etc/nginx/sites-available/reverse-proxy.conf
server {
    listen 80;
    location /some/path/ {
        proxy_pass http://example.com;
    }
}

NOTE: This will work for HTTP servers, but Nginx also supports other protocols.

  • Replace example.com with the IP address or hostname of the server you are forwarding to.
    • A port can also be specified with the hostname, such as 127.0.0.1:8080.

Enable the proxy

Enable the new configuring by creating a symbolic link to the sites-enabled directory:

ln -s /etc/nginx/sites-available/reverse-proxy.conf /etc/nginx/sites-enabled/reverse-proxy.conf

Proxy Non-HTTP servers

Nginx can also act as a reverse proxy for FastCGI, uwsgi, SCGI, and memcached.

Rather than using the proxy_pass directive shown above, replace it with the appropriate type:


Pass Headers

To configure what headers the reverse proxy server passes to the other server(s), define them in the same /etc/nginx/sites-available/reverse-proxy.conf configuration file.

Use the proxy_set_header directive to adjust the headers.

/etc/nginx/sites-available/reverse-proxy.conf
location /some/path/ {
        proxy_set_header HOST $host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_pass http://example.com;
}

NOTE: This defines three types of headers and sets them to the respective variables.

  • There are a lot of different options for passing headers.
  • Host: contains information about which host is being requested.
  • X-Forwarded-Proto: species if the request is HTTP or HTTPS.
  • X-Real-IP: contains the IP address of the requesting client.