Published: Sep 23, 2022

Nginx - Reverse Proxy

Reverse Proxy

A reverse proxy forwards client requests to back-end applications. Further tasks of a reverse proxy can be SSL Termination, caching, load balancing or rate limiting. It’s also possible to serve a static page (e.g. maintenance) if a back-end service is not reachable. reverse proxy overview

Configuration

Configuring a reverse proxy in nginx is pretty straightforward and only requires the proxy_pass directive. The following example also adds some useful headers (Host, X-Forwarded-For) to let the backend application know the adress of the reverse proxy (Host) and the requesting client (X-Forwarded-For). Further a custom error page is configured in case the backend application is not reachable (502 - Bad Gateway).

server {
        root /var/www/html;

        server_name example.com www.example.com;

        location / {
                proxy_pass http://localhost:3000;
                proxy_set_header Host $host;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }

        error_page 502 /maintenance.html;
        location = /maintenance.html {
                internal;
                root /var/www/html;
        }
}

Don’t forget to enable your site by symlinking sites-available/myapp to sites-enabled/myapp.