Shared proxy headers snippet
A Node.js, Python (Gunicorn, Uvicorn), or Go app bound to 127.0.0.1 (0.0.0.0 vs 127.0.0.1) sees every request as coming from 127.0.0.1, with Host: 127.0.0.1:3000 and scheme http, unless the proxy passes the original values. By default, nginx also speaks HTTP/1.0 to backends and closes the connection after each response.
Put the baseline directives in /etc/nginx/snippets/proxy-headers.conf. The reason matches add_header: proxy_set_header is an array directive, so adding one proxy_set_header inside a location drops every proxy_set_header inherited from server (Config anatomy). Pulling in a snippet with include avoids that trap.
proxy_http_version 1.1;Switches upstream requests to HTTP/1.1: required for WebSockets, backend keepalive pools, and chunked streaming.
default:proxy_http_version 1.0
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;Forwards the browser’s original Host (otherwise nginx sends $proxy_host, like 127.0.0.1:3000), client IP, proxy chain, and original scheme (http or https).
default:Host $proxy_host
If Cloudflare or another proxy sits in front of nginx, extract the real client IP with ngx_http_realip_module — covered in the rate-limiting and access guide.
Setup 1: reverse proxy to a web app (Node, Python, Go)
A baseline config for an app on 127.0.0.1:3000, plus a second /strip/ route showing trailing-slash prefix removal and timeouts.
server {
listen 80;
server_name app.example.org;
client_max_body_size 16m;Accepts traffic for the domain and raises the request body cap to 16m (the 1m default rejects most image uploads and attachments).
default:client_max_body_size 1m
location / {
include snippets/proxy-headers.conf;
proxy_set_header Connection "";
proxy_pass http://127.0.0.1:3000;Includes the shared snippet and clears Connection so nginx doesn’t send Connection: close and can reuse backend TCP sockets. Omitting a trailing slash on proxy_pass forwards the request path as-is.
proxy_connect_timeout 10s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}Timeouts for connecting, sending the request, and reading the response. Lowering proxy_connect_timeout to 5–10s avoids leaving users hanging for a full minute if the app is down.
default:proxy_connect_timeout 60sproxy_send_timeout 60sproxy_read_timeout 60s
location /strip/ {
include snippets/proxy-headers.conf;
proxy_set_header Connection "";
proxy_pass http://127.0.0.1:4000/;
}
}A separate service on port 4000 unaware of the /strip/ prefix: the trailing slash on proxy_pass strips /strip/ from the URI. /strip/users reaches the app as /users.
Trailing slash in proxy_pass: keep or strip the prefix
One trailing / on proxy_pass changes the URI your backend receives:
location |
proxy_pass |
Client request | URI sent to backend |
|---|---|---|---|
location /api/ |
http://127.0.0.1:3000; (no path) |
/api/users |
/api/users — passed unchanged |
location /api/ |
http://127.0.0.1:3000/; (has /) |
/api/users |
/users — /api/ replaced with / |
location /api/ |
http://127.0.0.1:3000/v2/; |
/api/users |
/v2/users — /api/ replaced with /v2/ |
location /api (no /) |
http://127.0.0.1:3000/; (has /) |
/api/users |
//users — double slash from mismatched / |
Setup 2: WebSocket without breaking regular HTTP
A WebSocket starts as an HTTP/1.1 request carrying Upgrade: websocket and Connection: Upgrade. Hardcoding proxy_set_header Connection "upgrade"; in a shared location sends that header on normal HTTP requests too — some app servers reject it or break keep-alive.
Use a map block in http instead: forward upgrade only when the client sent an Upgrade header, otherwise send close (or "" if proxying to an upstream with keepalive).
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}Lives in the http context (outside server). $connection_upgrade evaluates to upgrade only when the request includes an Upgrade header.
server {
listen 80;
server_name ws.example.org;
location /ws {
include snippets/proxy-headers.conf;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;Dedicated WebSocket endpoint at /ws (if HTTP and WebSocket share /, put the same Upgrade and $connection_upgrade lines inside location /).
proxy_read_timeout 1h;
proxy_send_timeout 1h;
proxy_pass http://127.0.0.1:3000;
}
}By default nginx drops the socket after 60 seconds with no frames. Raise both timeouts to an hour and keep ping/pong heartbeats every 20–30 seconds in the app.
default:proxy_read_timeout 60sproxy_send_timeout 60s
Setup 3: SSE streams and AI token streaming
proxy_buffering on is the default and helps regular pages: the backend writes its response quickly into nginx’s memory and moves on to the next request while nginx trickles bytes to a slow client.
For Server-Sent Events (Content-Type: text/event-stream), live logs, and LLM streaming, buffering gets in the way: tokens pile up inside nginx and the user stares at a blank screen until generation finishes.
server {
listen 80;
server_name sse.example.org;
location /sse {
include snippets/proxy-headers.conf;
proxy_set_header Connection "";Shared snippet (including proxy_http_version 1.1, needed for Transfer-Encoding: chunked) plus empty Connection.
proxy_buffering off;
proxy_cache off;
proxy_read_timeout 5m;
proxy_pass http://127.0.0.1:3000;
}
}Disables buffering and caching on this route so every data: … chunk reaches the browser as soon as the app calls flush(). Raise proxy_read_timeout to cover long model responses.
default:proxy_buffering onproxy_read_timeout 60s
If streaming and normal responses share the same location, you don’t need to disable buffering site-wide: return X-Accel-Buffering: no from the app on streaming responses, and nginx turns off buffering for that response alone.
How to check
- Validate syntax and reload:
sudo nginx -t && sudo systemctl reload nginx - Verify forwarded headers and
proxy_passslash handling (using your app or a small echo server on the backend port):curl -s -H "Host: app.example.org" http://127.0.0.1/api/users # {"path": "/api/users", "http": "HTTP/1.1", "host": "app.example.org", "x_real_ip": "127.0.0.1", "proto": "http"} curl -s -H "Host: app.example.org" http://127.0.0.1/strip/users # {"path": "/users", "http": "HTTP/1.1", "host": "app.example.org", ...} - Verify the WebSocket handshake — expect
101 Switching Protocols(useGETwith-D - -o /dev/null, not-I, becauseHEADdoes not upgrade WebSockets):curl -sD - -o /dev/null --max-time 2 --http1.1 \ -H "Host: ws.example.org" \ -H "Connection: Upgrade" -H "Upgrade: websocket" \ -H "Sec-WebSocket-Version: 13" -H "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==" \ http://127.0.0.1/ws # HTTP/1.1 101 Switching Protocols # Connection: upgrade # Upgrade: websocket - Verify SSE streaming with
-N(disablescurl’s own buffering):data:lines should appear one by one as the app flushes them, not all at once at the end:curl -sN -H "Host: sse.example.org" http://127.0.0.1/sse # data: token-1 # # data: token-2 # # data: token-3
If it doesn’t work
The backend receives /users instead of /api/users, or a double slash //users
- Cause
proxy_passincludes a path component — even a single trailing/(proxy_pass http://127.0.0.1:3000/;) — so nginx replaced the matchedlocationprefix with it.- Fix
- To pass the path unchanged, omit the trailing slash:
proxy_pass http://127.0.0.1:3000;. To strip the prefix cleanly, pair slashes on both:location /api/andproxy_pass http://127.0.0.1:3000/;.
The app builds redirects or links to http://127.0.0.1:3000 instead of https://app.example.org
- Cause
- nginx isn’t forwarding
HostandX-Forwarded-Proto, or the app ignores proxy headers without an explicit setting (trust proxyin Express,--proxy-headersin Uvicorn). - Fix
- Include
snippets/proxy-headers.confin thelocationblock and configure the app to trust proxy headers from127.0.0.1.
WebSockets fail with 400 or 426, or drop after exactly 60 seconds of idle time
- Cause
- nginx talks HTTP/1.0 to backends by default and doesn’t forward
UpgradeorConnection. Once upgraded, idle connections hitproxy_read_timeout(default60s). - Fix
- Set
proxy_http_version 1.1;,proxy_set_header Upgrade $http_upgrade;,proxy_set_header Connection $connection_upgrade;(viamap), and raiseproxy_read_timeoutto1h.
An SSE feed or AI chat stream stalls for tens of seconds, then dumps everything in one chunk
- Cause
proxy_bufferingisonby default, so nginx collects backend output in memory and flushes it in large blocks.- Fix
- Add
proxy_buffering off;andproxy_cache off;to the streaminglocation, or sendX-Accel-Buffering: nofrom the app response.
File uploads fail with 413 Request Entity Too Large, or slow report requests time out with 504 Gateway Timeout after one minute
- Cause
- nginx defaults
client_max_body_sizeto1mandproxy_read_timeoutto60s. - Fix
- Raise both limits inside the specific route’s
location(for exampleclient_max_body_size 32m;andproxy_read_timeout 180s;) instead of loosening them server-wide.