Sub topic 3
Reverse Proxies: Acting on Behalf of Servers
This chapter assumes you know how HTTP requests, responses, methods and headers work. It also assumes you know what IP addresses, ports and DNS names are, and what TLS provides. Nothing else is required.
What a reverse proxy is
A reverse proxy is a server that accepts requests from clients and forwards them to one or more backend servers. It then returns the backend's response to the client. It acts on behalf of the servers. Clients talk to the proxy's address and usually do not know the backends exist.
The "reverse" in the name describes which side the proxy serves. A forward proxy represents clients and sits near them. A reverse proxy represents servers and sits in front of them. The next chapter compares the two directly. Here we focus on the reverse proxy alone.
From the client's point of view there is one server at example.com. Behind that name, the proxy decides which backend handles each request.
Why systems put one in front of servers
A reverse proxy gives you one place to handle concerns that every backend would otherwise handle on its own. The common jobs are:
- Load balancing. Spread requests across several backends so no single one is overloaded.
- Failure handling. Stop sending traffic to a backend that is failing.
- TLS termination. Handle HTTPS at the edge so backends can speak plain HTTP on a private network.
- Caching. Answer repeated requests from stored responses without contacting a backend.
- Routing. Send
/api/to one service and/static/to another under a single public hostname. - Shielding. Hide backend addresses and absorb slow or malformed clients before they reach the application.
Later chapters cover load balancing, health checks, TLS termination and caching in depth. This chapter shows how the pieces fit together in a working configuration.
A minimal reverse proxy
The following nginx configuration distributes requests across two backends. It passes the original host and client address along, and it stops sending traffic to a backend for 30 seconds after three failed attempts.
upstream app_servers {
server 10.0.0.11:8080 max_fails=3 fail_timeout=30s;
server 10.0.0.12:8080 max_fails=3 fail_timeout=30s;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://app_servers;
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;
}
}Read it in two parts.
The upstream block
upstream app_servers names a group of backends. By default nginx distributes requests across them in round-robin order: the first request goes to 10.0.0.11, the second to 10.0.0.12, the third back to the first, and so on.
max_fails=3 and fail_timeout=30s set passive failure detection. If three attempts to reach a server fail within 30 seconds, nginx treats it as unavailable for the next 30 seconds. "Passive" means nginx learns about failures only from real traffic, not from separate probe requests.
The server block
listen 80 and server_name example.com tell nginx to accept requests for that name on port 80. location / matches every path. proxy_pass http://app_servers sends the matching request to the upstream group.
The proxy_set_header lines matter more than they look. By default nginx rewrites the Host header to the name in proxy_pass, and the backend sees the proxy's address as the client. These lines correct both problems.
What the backend sees
A request that goes through a reverse proxy is a new connection. The backend sees a TCP connection from the proxy's IP address, not the client's. If you do nothing, every request in your access logs appears to come from the proxy.
To preserve the original information, the proxy adds headers:
X-Forwarded-For: 203.0.113.7, 10.0.0.5
X-Forwarded-Proto: https
Forwarded: for=203.0.113.7;proto=https;host=example.comX-Forwarded-Forlists client addresses, with the original client first and each proxy that handled the request appended after it.$proxy_add_x_forwarded_forin nginx appends the connecting address to any value already present.X-Forwarded-Protorecords whether the client usedhttporhttps. This matters when the proxy terminates TLS, because the backend only sees plain HTTP.Forwardedis the standardized form (RFC 7239). It carries the same information in one header. Many tools still use theX-Forwarded-*headers, so check which one your application framework reads.X-Real-IPis a nginx convention that carries a single client address.
A common safe pattern is to read the address from the right side of X-Forwarded-For, skipping entries that belong to your own proxies. The first entry the client controls is the first one you cannot verify.
Routing under one hostname
A reverse proxy can use the path, host name or other request properties to choose a destination. This lets several services share one public address.
upstream api_servers {
server 10.0.1.21:9000;
}
upstream web_servers {
server 10.0.0.11:8080;
server 10.0.0.12:8080;
}
server {
listen 80;
server_name example.com;
location /api/ {
proxy_pass http://api_servers;
proxy_set_header Host $host;
}
location / {
proxy_pass http://web_servers;
proxy_set_header Host $host;
}
}nginx picks the most specific matching location. A request for /api/orders goes to api_servers. Everything else goes to web_servers. This is the starting point for the API gateway pattern covered in a later chapter.
TLS at the proxy
Reverse proxies often terminate TLS. The client opens an HTTPS connection to the proxy, and the proxy forwards plain HTTP to the backends.
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/nginx/certs/example.com.crt;
ssl_certificate_key /etc/nginx/certs/example.com.key;
location / {
proxy_pass http://app_servers;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
}
}Certificates and keys live in one place instead of on every backend. The backend learns that the client used HTTPS through X-Forwarded-Proto. A later chapter covers re-encrypting traffic to the backends when the internal network is not trusted.
Caching at the proxy
A reverse proxy can store responses and serve them without contacting a backend. This reduces backend load and shortens response time for repeated requests.
# In the http {} context
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=app_cache:10m max_size=1g inactive=60m;
server {
listen 80;
server_name example.com;
location /static/ {
proxy_pass http://app_servers;
proxy_cache app_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_use_stale error timeout updating;
}
}proxy_cache_path defines where cached files live on disk and how much space they may use. keys_zone=app_cache:10m reserves 10 MB of shared memory for cache keys. proxy_cache_valid 200 302 10m keeps successful and redirect responses for ten minutes. proxy_cache_use_stale serves an old copy if the backend fails or is slow, which keeps the site partly usable during an outage.
Cache only responses that are the same for every client. Caching a response that contains one user's private data and serving it to another user is a serious data leak.
Request flow in detail
The sequence below shows one request through a reverse proxy that terminates TLS and caches.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Backend logs show the proxy's IP for every request | Backend reads the connection address, not the forwarding header | Read `X-Forwarded-For` or `Forwarded`, trusting only known proxies |
| Backend generates `http://` links or redirect loops after TLS termination | Backend does not know the client used HTTPS | Send `X-Forwarded-Proto` and make the application honor it |
| Backend serves the wrong site or a default page | `Host` header was rewritten to the upstream name | Set `proxy_set_header Host $host` |
| `502 Bad Gateway` | Proxy cannot connect to any backend, or the backend closed the connection | Check backend address, port, firewall and that the service is running |
| `504 Gateway Timeout` | Backend did not answer within the proxy's timeout | Investigate slow backend work; raise `proxy_read_timeout` only if the delay is expected |
| One user sees another user's data | A private response was cached | Restrict caching to shared content and respect `Cache-Control: private` |
Costs to keep in mind
A reverse proxy adds one network hop, so each request pays a small amount of extra latency. It also becomes a single point of failure if you run only one. A later chapter covers running several proxy instances so that the loss of one does not take the site down. Finally, it adds configuration that must stay consistent with the applications behind it, especially headers and timeouts.
Exercise
Your application sits behind an nginx reverse proxy that terminates TLS. Users report that after logging in, they are redirected to an http:// URL and the login loop fails. Access logs on the backend also show the same IP address for every request. Name the two headers the proxy should send and what each one fixes.
Show answer
Send X-Forwarded-Proto (set to $scheme) so the application knows the client used HTTPS and builds https:// links and redirects. Send X-Forwarded-For (using $proxyaddxforwardedfor) so the backend can log the original client address instead of the proxy's address. The application must be configured to read both headers, and to trust them only when they come from the proxy.
Exercise
In the upstream block, what does maxfails=3 failtimeout=30s do, and why is it called passive failure detection?
Show answer
After three failed attempts to reach a server within 30 seconds, nginx stops sending requests to that server for the next 30 seconds. It is passive because nginx learns about failures only from real client requests that fail, not from separate health-check probes sent on a schedule.