HTTP, TLS & Web Performance

Reverse Proxies Explained

Learn what a reverse proxy does, why sites put one in front of their applications, and how to configure one without common mistakes.

Key takeaways

  • A forward proxy acts for clients, while a reverse proxy acts for servers.
  • Common jobs include TLS termination, routing by hostname or path, caching, compression and load balancing.
  • The application sees the proxy's address unless the proxy passes the original details in headers.
  • Forwarded headers can be forged, so an application should trust them only when they come from its own proxy.
  • A reverse proxy is also a single point of failure and needs monitoring, updates and sometimes a twin.

A reverse proxy is a server that accepts requests from clients on behalf of one or more other servers, forwards each request to the right one, and passes the answer back. Visitors talk to the proxy and usually never learn what sits behind it.

Sites use one to handle HTTPS in a single place, to run several applications behind one address, to cache and compress responses, and to keep application servers off the public internet. If you've seen nginx, Apache, Caddy, HAProxy or Traefik in front of an app, you've seen a reverse proxy.

Forward and reverse

A forward proxy sits near the users. A school or company may send outgoing web traffic through one to filter or log it, and the websites see the proxy as the visitor.

A reverse proxy sits near the servers. Clients on the internet connect to it as though it were the website. The servers it forwards to are called upstreams or backends.

The software can be similar. The difference lies in whom it represents.

What a reverse proxy can connect
Reverse proxy One public entrance Logs A record of every request Cache Reuses suitable responses Static files Served straight from disk Visitors Connect over HTTPS Certificates Managed in one place Web app Handles main pages API service Reached by path or hostname Reverse proxy One public entrance Visitors Connect over HTTPS Certificates Managed in one place Web app Handles main pages API service Reached by path or hostname Static files Served straight from disk Cache Reuses suitable responses Logs A record of every request

What it's good for

TLS termination. The proxy holds the certificates and does the encryption. Applications behind it can be simpler. Traffic between proxy and application stays on the same machine or a trusted network, or is encrypted again when it crosses anything less trusted. Automated renewal is covered in Let's Encrypt and ACME.

Routing. One public IP address can serve many sites. The proxy looks at the hostname or path and chooses an upstream: /api/ to one service, everything else to another.

Protection and tidiness. Application servers can listen only on a private address. The proxy can limit request sizes and rates, add security headers, and shield a fragile application from slow clients by buffering.

Performance. It serves static files efficiently, applies compression, caches responses and speaks newer HTTP versions to visitors even if the application doesn't.

Distribution. With several copies of an application, the same proxy can share requests between them. That's the subject of load balancers.

A request's journey

Through a TLS-terminating reverse proxy
Browser Proxy Application HTTPS request for /orders 1 Forward with client details 2 Adds forwarded headers Response from the app 3 Encrypted, compressed reply 4 Browser Proxy Application HTTPS request for /orders 1 Forward with client details 2 Adds forwarded headers Response from the app 3 Encrypted, compressed reply 4

There are two separate connections here. The proxy can keep its connections to the application open and reuse them, and it can read and modify anything passing through.

Several services behind one address

Say you run a website, a small API and a wiki on a single machine. Only one program can listen on port 443 for a given address. The proxy takes that port, and each service listens on its own local port.

You then choose how to divide them. Hostnames such as www.example.com, api.example.com and wiki.example.com keep the services cleanly separate, with their own cookies and paths. Dividing by path, as in example.com/wiki/, needs only one name, but each application has to know that it lives under a prefix, or its links and redirects will point to the wrong place. When you have the choice, hostnames usually cause fewer surprises.

For the client to indicate which name it wants during an encrypted connection, it sends the Server Name Indication field in the TLS handshake, so the proxy can present the matching certificate. All current browsers do this. A default server block that rejects unknown hostnames is worth adding, so stray requests aimed at your IP address don't land in whichever application happens to be listed first. Choosing between the two layouts also has publishing consequences, covered in subdomains vs. subdirectories.

A basic nginx configuration

This forwards a site to an application listening locally on port 3000:

server {
    listen 443 ssl;
    server_name app.example.com;
    ssl_certificate     /etc/ssl/app.example.com/fullchain.pem;
    ssl_certificate_key /etc/ssl/app.example.com/privkey.pem;

    location / {
        proxy_pass http://127.0.0.1:3000;
        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;
    }
}

The certificate paths are examples. Test the syntax with nginx -t before reloading.

One detail trips people up. In proxy_pass, adding a path or trailing slash after the upstream address changes how the matched location prefix is rewritten. If your application receives unexpected paths, look there first.

Caddy offers a very short form for simple cases, with automatic HTTPS for a public domain that points at the machine:

caddy reverse-proxy --from app.example.com --to localhost:3000

Telling the application the truth

From the application's side, every connection now comes from the proxy, over whatever protocol the proxy uses. Without extra information, logs show one address, redirects point at http:// or an internal name, and rate limits treat all visitors as one.

The conventional headers are X-Forwarded-For, X-Forwarded-Proto and X-Forwarded-Host. RFC 7239 defines a standard Forwarded header that combines them, though the older names remain very common.

These are ordinary request headers, so any client can send fake ones. Two rules keep you safe:

  1. The outermost proxy should overwrite, or carefully append to, what clients sent.
  2. The application should believe the headers only when the connection comes from a known proxy address, and should count hops from the trusted end of the list.

Most web frameworks have a "trusted proxies" setting for this. An echo of your request headers shows what arrives at a server from your own browser.

WebSockets, streaming and long requests

WebSocket connections begin as HTTP requests that ask to upgrade. Some proxies pass this through automatically; nginx needs it spelled out:

proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";

Server-sent events and other streaming responses can stall if the proxy buffers them. Turn buffering off for those paths, and raise read timeouts for connections that are meant to stay quiet for a while. More background is in WebSockets and server-sent events.

Caching at the proxy

A reverse proxy can store responses and serve them without bothering the application. Even a few seconds of caching on a busy public page can turn thousands of identical requests into one.

Be strict about what's eligible. Honor Cache-Control, bypass the cache for requests with session cookies or authorization, and include anything that changes the page in the cache key. The directive meanings are in browser caching and Cache-Control.

A CDN is essentially a globally distributed reverse proxy. Many sites use both: a network at the edge and their own proxy at the origin. An API gateway is another close relative, adding authentication, quotas and API management.

Headers, limits and security settings

Because every response passes through it, the proxy is a convenient place to set policy once. Common additions are Strict-Transport-Security, which tells browsers to use HTTPS in future, and X-Content-Type-Options: nosniff. Apply Strict-Transport-Security only when you're sure HTTPS works for every host it will cover; see HSTS.

You can also limit request rates per client, cap body and header sizes, require a password or client certificate on an administrative path, and hide version details in the Server header. Hiding versions is minor tidiness. Updating the software is what protects you.

Avoid putting business rules in proxy configuration. A few redirects and access limits are fine, but long chains of rewrites become hard to test and easy to break. If a rule depends on who the user is or what they own, it belongs in the application.

When you change the configuration, check it, reload instead of restarting where your software supports it, and request a few important pages straight afterwards. A reload keeps existing connections alive while new ones pick up the new settings.

What can go wrong

  • 502 Bad Gateway. The proxy couldn't get a valid reply. Check that the application is running and listening where the proxy expects. See 502 and 504 errors.
  • 504 Gateway Timeout. The application took too long. Raising the timeout hides the symptom; look for the slow work.
  • 413 errors on uploads. The proxy has its own request size limit, such as client_max_body_size in nginx.
  • Redirect loops. The application thinks the request was plain HTTP and redirects to HTTPS forever. Pass and honor the original protocol.
  • Internal ports left open. If the application also listens publicly, visitors can bypass every rule on the proxy. Bind it to a private address or firewall it.
  • Disagreement about requests. If the proxy and application interpret malformed requests differently, attackers can exploit the gap. Keep both updated and let the proxy reject invalid input.

Do you need one?

For a static site on managed hosting, the provider already runs one for you. For a single application on your own server, a reverse proxy is usually worth it for certificate handling and safety alone. For several services on one machine, it's close to essential.

The cost is another piece of configuration to understand. Keep the file small, put it in version control, review it when you add services, and watch the proxy's error log, which is often the quickest route to the cause of an outage.

Reading the logs

The proxy's access log is a single record of everything that arrived. Add the upstream's response time and status to the log format, and slow or failing requests become easy to attribute. If total time is high while upstream time is low, the delay lies with a slow client or a large transfer. If both are high, look in the application. Rotate logs so they don't fill the disk, which is a surprisingly common way for a healthy server to stop working.

Common questions

Can a reverse proxy see encrypted traffic?

Yes, if it terminates TLS. It decrypts requests in order to route them. A proxy can alternatively pass encrypted connections through, routing by the server name offered in the TLS handshake, but then it can't inspect, cache or modify the contents.

Does it hide my server's address?

Only if nothing else reveals it. Old DNS records, outgoing connections from the application, or mail sent directly from the machine can all expose it.

Written for 4Internet with AI writing tools and not reviewed line by line by a person. Check anything you rely on with the maker, provider or standard concerned. Report an error.

Keep reading

All 45 articles in HTTP, TLS & Web Performance →

Latest news on this topic