Bottom line: Almost every 502 and 504 on a WebSocket upgrade behind Nginx comes down to two things: the hop-by-hop Upgrade and Connection headers are not forwarded to the backend, and proxy_read_timeout is still sitting at its 60-second default. Fix the headers, raise the timeout, and add a ping keepalive on the backend.

WebSocket proxying in Nginx has been supported since 1.3.13, but the configuration is not something you get for free. A plain proxy_pass block that works fine for HTTP will silently break the upgrade: the client sends Upgrade: websocket, Nginx strips it because it is a hop-by-hop header, the backend never sees the protocol switch request, and the connection either hangs until a timeout fires (504) or the upstream closes it and Nginx reports 502. Both symptoms point at the same root cause, and both are fixed in the same location block.

Why the upgrade fails in the first place

HTTP/1.1 protocol switching relies on two headers: Upgrade: websocket and Connection: Upgrade. Both are hop-by-hop, meaning they are scoped to a single transport connection and, per the spec, must not be forwarded by a proxy. Nginx follows that rule. If you do nothing, the backend receives a request with neither header, treats it as an ordinary GET, and responds with a normal HTTP response. The client is waiting for a 101 Switching Protocols and gets a 200 OK instead, or the socket stalls.

Nginx has had a special operating mode since 1.3.13: if the backend returns 101 and the client asked for a protocol switch via Upgrade, Nginx sets up a tunnel between the two. The catch is that the backend has to know to return 101, which means you have to re-inject the headers explicitly on the proxy side.

There is a second, less obvious requirement: the upstream connection must be HTTP/1.1. HTTP/1.0 has no upgrade mechanism. Older documentation and countless Stack Overflow answers include proxy_http_version 1.1; for this reason. As of Nginx 1.29.7 that directive is no longer required for the upgrade path — the documentation now comments it out in the canonical example — but if you are on anything older, leaving it in is harmless and leaving it out will break you. Check your version before you delete it.

The minimum working config

This is the smallest block that actually upgrades:

1
2
3
4
5
6
location /chat/ {
proxy_pass http://backend;
proxy_http_version 1.1; # required before 1.29.7
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}

The hardcoded Connection "upgrade" works, but it lies on every non-WebSocket request to the same location — you are telling the backend to upgrade a plain GET. The documented fix is a map that sets Connection based on whether the client actually sent an Upgrade header:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
http {
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}

server {
location /chat/ {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
}
}
}

Use the map form. It costs nothing and it means the same location can serve both the WebSocket endpoint and any regular HTTP traffic on the same path prefix without sending bogus upgrade requests upstream.

Timeouts: the 504 you get 60 seconds later

Nginx closes a proxied connection if the backend transmits no data within 60 seconds. That is the documented default for proxy_read_timeout. For a chat app that sends a message every few seconds this never bites. For a dashboard that pushes an update every five minutes, or an idle notification socket, it bites constantly — and it looks like a 504 in the access log even though nothing is actually wrong with the backend.

Two fixes, and you want both.

Raise proxy_read_timeout on the WebSocket location. There is no universally correct number; pick one larger than your longest expected quiet period. For most interactive applications something in the 300s–3600s range is reasonable. For a socket that is genuinely idle for hours, a very long timeout just hides dead connections, which is why the second fix matters more.

Make the backend send WebSocket ping frames on an interval. A ping resets the read timeout and doubles as a liveness check — if the peer is gone, the pong never arrives and you can tear the connection down cleanly instead of leaking it. A ping every 30–60 seconds keeps the connection alive under any sane proxy_read_timeout and lets you detect half-open TCP connections that would otherwise sit there until the kernel gives up.

1
2
3
4
5
6
7
8
9
10
11
12
location /ws/ {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;

proxy_read_timeout 3600s;
proxy_send_timeout 3600s;

# do not buffer an upgraded stream
proxy_buffering off;
}

proxy_send_timeout governs writes in the other direction and has the same 60-second default; set it to match. proxy_buffering off is not strictly required for correctness but prevents Nginx from holding frames in a buffer when the client is slow, which shows up as mysterious latency on busy sockets.

Choosing timeout values

The defaults are tuned for short-lived HTTP requests, not for long-lived tunnels. Here is how the relevant directives compare out of the box versus what a WebSocket location typically needs:

Directive Default Typical WebSocket value What it controls
proxy_read_timeout 60s 300s–3600s Max gap between reads from upstream
proxy_send_timeout 60s 300s–3600s Max gap between writes to upstream
proxy_connect_timeout 60s 5s–10s Time to establish the upstream TCP connection
proxy_http_version 1.0 1.1 (pre-1.29.7) Upstream protocol; upgrade needs 1.1
proxy_buffering on off Whether responses are buffered before relay

proxy_connect_timeout is worth tightening while you are in there. A 60-second connect timeout means a dead backend ties up a worker for a full minute before Nginx returns 502. Ten seconds is generous for anything on a LAN or in the same datacenter.

Diagnosing which failure you actually have

The status code tells you less than you think, because both 502 and 504 can come from the same misconfiguration at different stages. Work from the logs.

Check the error log first. upstream prematurely closed connection while reading response header from upstream means the backend accepted the TCP connection and then dropped it — usually because it did not understand the request, which is what happens when the Upgrade header is missing. upstream timed out (110: Connection timed out) while reading response header from upstream is the 60-second read timeout firing.

Confirm what the backend actually received. If you control it, log the incoming headers on the upgrade endpoint and look for Upgrade and Connection. If they are absent, the proxy config is wrong. If they are present and the backend still refuses, the problem is on the application side, not in Nginx.

Test the upgrade without a browser. curl will show you the response status and headers directly:

1
2
3
4
5
6
curl -i -N \
-H "Connection: Upgrade" \
-H "Upgrade: websocket" \
-H "Sec-WebSocket-Version: 13" \
-H "Sec-WebSocket-Key: $(openssl rand -base64 16)" \
https://example.com/ws/

A working setup returns HTTP/1.1 101 Switching Protocols with Upgrade: websocket and Connection: Upgrade in the response. A 200 means the upgrade never happened. A 400 from the backend usually means the headers arrived but the Sec-WebSocket-* values were rejected. A 502 with nothing in the backend log means Nginx could not talk to upstream at all — check proxy_pass, the listen address, and whether the backend is bound to a reachable interface.

Watch the connection state while a client is connected. ss -tnp on the Nginx host should show an established connection to the backend port for the duration of the socket. If it disappears after roughly 60 seconds, you have found the timeout.

Pitfalls that waste the most time

Forgetting the map and hardcoding Connection "upgrade". Works until the same location serves a health check or a plain REST call, at which point the backend gets an upgrade request it did not ask for. Use the map.

Setting proxy_read_timeout but not sending pings. The timeout stops firing, but dead peers now linger for the full timeout duration. Pings are the actual fix; the timeout is just headroom.

Terminating TLS in front of Nginx and losing the upgrade. If a load balancer or CDN sits in front, it needs to forward the upgrade too. A 502 that only appears in production and never in staging is almost always this.

Buffering the stream. With proxy_buffering on (the default), Nginx may hold small frames waiting for a buffer to fill. Latency on a chat socket goes from milliseconds to seconds. Turn it off for the WebSocket location.

Assuming the version. The proxy_http_version 1.1 requirement changed in 1.29.7. Copy-pasting a config between a new and an old host without checking nginx -v produces failures that look random.

Rate limits applied to the upgrade path. If you have limit_req or limit_conn on the server block, a client reconnecting after a network blip can get 503s that look like WebSocket failures. Scope the limits so they do not apply to the socket endpoint, or size them for reconnection storms.

FAQ

Why do I get a 502 instead of a 101 when the headers are missing?

The backend receives an ordinary HTTP request without the upgrade headers, responds normally, and the client’s expectation of a protocol switch is never met. Depending on how the client and backend handle the mismatch, the connection is closed and Nginx reports it as a bad gateway. The 502 is a symptom of the failed handshake, not a networking problem.

Do I still need proxy_http_version 1.1?

On Nginx 1.29.7 and later, no — the upgrade path no longer requires it and the official example comments it out. On anything earlier, yes, because HTTP/1.0 has no upgrade mechanism. Run nginx -v before removing it from an existing config.

What should I set proxy_read_timeout to?

Larger than the longest quiet period you expect on the socket. For interactive apps, 300s to 3600s covers most cases. Pair it with backend ping frames every 30–60 seconds so idle-but-alive connections stay up and dead ones get detected rather than lingering.

Can I use one location for both WebSocket and regular HTTP?

Yes, with the map $http_upgrade $connection_upgrade pattern. The Connection header is set to upgrade only when the client actually sent an Upgrade header, and to close otherwise. Hardcoding "upgrade" breaks the non-WebSocket requests on the same path.

Why does the connection drop at almost exactly 60 seconds?

That is the documented default for proxy_read_timeout: Nginx closes the connection if the backend transmits no data within 60 seconds. Either raise the timeout, make the backend send pings, or both. The near-exact 60-second interval is the tell.

Does proxy_buffering off matter for WebSockets?

It is not required for the upgrade to succeed, but leaving buffering on can add latency to small frames because Nginx waits to fill a buffer before relaying. For anything latency-sensitive, turn it off on the WebSocket location.