Understanding the role of a reverse proxy

What Nginx actually does in front of your application, why you never expose the app directly, and how to write a configuration that will not betray you in production.

6 min readBy Valentin Flückiger

Almost every web application I operate runs behind a reverse proxy. Not out of tradition, and not because that is what the tutorials do: because without it, a large part of the operational work becomes impossible to do properly.

This guide explains what that layer actually does, why it exists, and how to configure it without creating problems for later.

Proxy, reverse proxy: the difference

The two words look alike and describe opposite roles.

A conventional proxy acts on behalf of the client. Your browser asks it to fetch a page, it does, and hands you the result. The remote server sees the proxy, not you.

A reverse proxy acts on behalf of the server. The client believes it is talking to your application; in reality it is talking to the proxy, which forwards the request to the application and returns the response. The client sees the proxy, not the application.

It is the second case that matters here: a single, controlled front door in front of one or more applications.

Why not expose the application directly

A Node, Python or Ruby server is perfectly capable of listening on a port and answering HTTP requests. Technically, nothing stops you from exposing it on port 443 and leaving it at that. In practice you give up a great deal.

1. Encryption

The proxy terminates TLS. It holds the certificates, negotiates with the client, and forwards the request in clear over the loopback interface. The application never has to know what a certificate is, nor be restarted when one is renewed.

That is a genuine gain: certificates renew every two or three months. With the proxy, renewal is a configuration reload that drops no connections. Without it, it is an application restart.

2. Static files

An image, a stylesheet, a font: there is no reason for an application to serve those. The proxy reads the file from disk and sends it, with the right cache headers. It is faster, and it leaves the application to do what only it can do.

3. Exposed surface

The application listens on 127.0.0.1. It is reachable only from the machine itself. Everything from outside goes through the proxy, where you can filter, rate-limit, log and refuse.

4. Several applications, one address

One server, one IP address, ten sites. The proxy looks at the requested host name and routes to the right application. That is exactly what lets several projects share a machine without stepping on each other.

5. Security headers

Content security policy, HSTS, framing protections: these can be set in one place for every site, rather than reimplemented in each application.

A minimal configuration, annotated

Here is an Nginx configuration cut down to essentials, for a Node application listening on port 3000.

server {
    listen 80;
    server_name example.com www.example.com;

    # Let ACME validation through, redirect everything else.
    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }

    location / {
        return 301 https://example.com$request_uri;
    }
}

server {
    # http2 as a listen parameter: the separate "http2 on;" directive
    # only exists from nginx 1.25.1 onwards.
    listen 443 ssl http2;
    server_name example.com;

    ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    # Build-versioned files carry a hash in their name: their content
    # never changes, so they can be kept for a very long time.
    location /_next/static/ {
        alias /var/www/mysite/.next/static/;
        expires 1y;
        add_header Cache-Control "public, immutable";
    }

    location /uploads/ {
        alias /var/www/mysite/public/uploads/;
        expires 30d;
    }

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;

        # Without these two lines, WebSockets do not get through.
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";

        # Without these, the application believes everyone is
        # connecting from 127.0.0.1 over plain HTTP.
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        proxy_read_timeout 60s;
    }
}

The mistakes that cost time

Forgetting the X-Forwarded-* headers

This is the most common mistake, and the most insidious, because the site works. It is the side effects that show up later:

  • Logs record 127.0.0.1 for every visitor. Your per-IP rate limiting therefore limits everyone together, or no one.
  • The application generates http:// URLs while the visitor is on https://, breaking redirects and absolute links.
  • Secure cookies are not sent, because the application believes it is running in clear.

Getting proxy_pass and the trailing slash wrong

proxy_pass http://127.0.0.1:3000; and proxy_pass http://127.0.0.1:3000/; do not do the same thing. With the trailing slash, Nginx replaces the part matched by the location; without it, it forwards the full path. One slash too many and all your URLs are shifted.

Leaving timeouts at their defaults

A long request — an export, an image job — will be cut off by the proxy before the application has finished, and the client will see a 504 with no explanation. Adjust proxy_read_timeout deliberately, or better: make the work asynchronous.

Testing in production

nginx -t validates the syntax before reloading. On a machine hosting several sites, reloading an invalid configuration does not only break yours: it breaks all the others. The rule is simple and admits no exceptions:

sudo nginx -t && sudo systemctl reload nginx

The && is not decorative. It guarantees the reload only happens if the test passes.

The invisible trap: upgrade-insecure-requests

A real case, because it cost me time and because it is particularly devious.

The upgrade-insecure-requests directive in a content security policy asks the browser to fetch every resource over HTTPS, even where the page references it over HTTP. It is an excellent directive on a production site with a valid certificate.

On a preview served in clear at http://ip-address:3092 it is catastrophic: the browser tries to fetch every stylesheet and script over HTTPS, there is no TLS listener on that port, everything fails, and the site renders as raw HTML with no styling at all.

The cruellest part is how it escapes verification:

  • curl does not read content security policies. Everything looks fine.
  • On localhost and 127.0.0.1, browsers treat the origin as already trustworthy and do not apply the upgrade. Testing locally, you see nothing.

The lesson generalises well beyond this case: always test on the real host name, in a real browser. A command-line check cannot see what the browser enforces.

Load balancing across several application instances

As soon as an application runs in more than one copy, the proxy becomes a load balancer too.

upstream mysite {
    # least_conn rather than the default round robin: sends to the
    # instance with the fewest active connections. More appropriate
    # when request durations vary a lot.
    least_conn;

    server 127.0.0.1:3000 max_fails=3 fail_timeout=30s;
    server 127.0.0.1:3001 max_fails=3 fail_timeout=30s;

    keepalive 32;   # reuse upstream connections
}

server {
    location / {
        proxy_pass http://mysite;
        proxy_next_upstream error timeout http_502 http_503;
    }
}

max_fails and fail_timeout temporarily take a failing instance out of rotation. proxy_next_upstream replays the request elsewhere if an instance fails — enable it only for requests that are safe to replay: a replayed POST can create two orders.

Mind sessions. If your application keeps state in memory, two requests from the same user landing on two instances behave inconsistently. The right answer is to move state out of memory, not to pin clients to an instance.

And mind the database. Load balancing assumes several processes can write to the database concurrently. With SQLite they cannot: moving to several instances means migrating to a client-server database.

Rate limiting and filtering

The proxy is the right place to absorb what should never reach the application at all.

# A 10 MB shared zone tracks roughly 160,000 addresses.
limit_req_zone $binary_remote_addr zone=general:10m rate=30r/s;
limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;

server {
    location / {
        # burst absorbs legitimate bursts; nodelay serves them
        # immediately instead of spreading them out.
        limit_req zone=general burst=50 nodelay;
        proxy_pass http://127.0.0.1:3000;
    }

    # Much stricter where it matters.
    location /login {
        limit_req zone=login burst=3;
        proxy_pass http://127.0.0.1:3000;
    }
}

Two important caveats.

Behind another proxy, $binary_remote_addr is wrong. If a content delivery network sits in front, every request appears to come from it, and you rate-limit everyone together. You then need the forwarded address, after configuring set_real_ip_from to trust only legitimate intermediaries.

In IPv6, limiting by exact address is useless. A client often holds an entire /64 and can change address at will. Limit on the prefix.

And if you do not use Nginx?

Nginx is not the only option, and the reasoning is unchanged.

  • Caddy obtains and renews certificates by itself. Its configuration fits in a few lines. It is often the best choice when starting out.
  • Traefik discovers services dynamically, which matters when containers come and go.
  • HAProxy excels at load balancing, with very fine control over upstream health.

I use Nginx because I know it well, its documentation is excellent and its behaviour is predictable. Those are good reasons, but they are not universal ones.

What to take away

A reverse proxy is not an added layer of complexity: it is the layer that lets everything else stay simple. The application only produces responses. Encryption, caching, static files, host-based routing and security headers live elsewhere, in one place for every project, and can be changed without redeploying anything.

If you remember only three lines from this guide: make the application listen on 127.0.0.1, forward the X-Forwarded-* headers, and never reload Nginx without running nginx -t first.

Tags

  • Linux
  • Nginx
  • Hosting
  • Security