Lesson 2 of 9 · 24m
Reverse Proxy Patterns That Survive Production
Forwarding identity correctly, handling prefixes and WebSockets, and setting buffering plus timeout behavior before users teach you the hard way.
A reverse proxy is not a URL rewriter with delusions of grandeur. It is the boundary between hostile or flaky internet clients and application processes that should be allowed to assume a mostly sane world. If you do not deliberately configure that boundary, nginx will faithfully preserve some client properties, destroy others, and buffer things in ways nobody expected.
Preserve client identity deliberately
Applications need the original scheme, host, and client address. nginx will not magically know what your framework expects, so send a consistent set of forwarding headers:
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host $host;Prefix stripping is easy to get subtly wrong
location /api/ { proxy_pass http://app_upstream/; } # strips /api/
location /status/ { proxy_pass http://app_upstream; } # preserves /status/That trailing slash on the upstream URI is not decoration. It changes how nginx rewrites the request path. Teams lose hours when the application expects /users but receives /api/users, or the reverse. Decide whether the edge owns path structure or merely transports it, then document the choice in the config.
WebSockets need protocol upgrades
A WebSocket request is HTTP only long enough to negotiate an upgrade. Proxying it like a normal request leaves dead connections and confusing client retries.
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
location /socket/ {
proxy_pass http://realtime_upstream;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_read_timeout 3600s;
}Buffering is protection until it becomes delay
nginx normally buffers upstream responses so slow clients do not pin application workers. That is good for HTML and JSON, bad for streaming, server-sent events, large downloads, and interactive protocols.
location /downloads/ {
proxy_pass http://files_upstream;
proxy_buffering off;
proxy_request_buffering on;
}proxy_buffering off affects responses from upstream. proxy_request_buffering affects the client request body. Turning both off because of one timeout report is a recipe for application workers pinned by slow clients.
Field notes
- Never trust forwarded headers unless the edge that adds them is the only reachable path.
- Test prefix routes with
curl -iagainst nginx and a backend echo endpoint; path rewrites are empirical, not vibes. - Timeouts are policy: connect, read, and send mean different things and must be set independently.
Was this lesson helpful?