Chapter 8 · Lesson 7 of 8
Web servers and proxies

Websockets through a proxy: nginx Upgrade headers and SSE

A websocket starts as an HTTP request with an Upgrade header, so a proxy must pass that header, use HTTP 1.1 to the app and keep idle connections open long enough.

By the end you will

Proxy a websocket and a server-sent events stream through nginx, and recognise the 400, 502 and dropped-connection symptoms.

Time
22 min
Level
Intermediate
Check
4 questions
You need
  • An nginx reverse proxy already forwarding to an app
  • An app that serves websockets or server-sent events

Websockets work fine in development and then fail behind nginx, usually with a quiet 400 or a connection that closes after a minute. The cause is almost always a missing header or a timeout, and it shows up the same way over TLS in nginx. This lesson shows the three lines nginx needs, how to handle long-lived streams, and why Caddy users rarely think about it.

How it works#

A websocket begins as a normal GET with Upgrade: websocket and Connection: Upgrade. If the server agrees, it replies 101 Switching Protocols and the same TCP connection then carries messages in both directions. Both headers are hop-by-hop, meaning a proxy is expected to consume them instead of passing them along. So nginx drops them by default, and it also speaks HTTP 1.0 to the app, which has no upgrade at all. The app sees a plain request and answers with an error.

A reverse proxy therefore has to rebuild the handshake on its second connection, and then keep the connection open. A websocket may be idle for minutes, and proxy timeouts see idle as dead.

Step 1: Add the map block#

In the http block (on Ubuntu, a file in /etc/nginx/conf.d/ works):

nginx
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

$http_upgrade holds the client’s Upgrade header. The map sets $connection_upgrade to upgrade when a client asks for it and close for ordinary requests. That lets one location serve both websocket and normal traffic.

Step 2: Configure the location#

nginx
location /socket/ {
    proxy_pass http://127.0.0.1:3000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection $connection_upgrade;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_read_timeout 3600s;
}
  • proxy_http_version 1.1 allows the upgrade.
  • The two Upgrade and Connection lines pass the handshake on.
  • Host and the forwarded headers are the same as in nginx reverse proxy for a Node app. Many apps check Origin against the host, so keep them.
  • proxy_read_timeout 3600s lets a socket sit idle for an hour. Choose a number that fits your app. A better design is for the app to send a ping every 20 to 30 seconds, so any proxy in the path sees traffic.

Test and apply with sudo nginx -t && sudo systemctl reload nginx. A reload does not cut existing websockets at once, but old workers linger until those sockets close.

Step 3: Proxy server-sent events#

Server-sent events (SSE) are a one-way stream over plain HTTP, not a websocket. They need no Upgrade, but buffering breaks them:

nginx
location /events {
    proxy_pass http://127.0.0.1:3000;
    proxy_http_version 1.1;
    proxy_set_header Connection "";
    proxy_buffering off;
    proxy_cache off;
    proxy_read_timeout 3600s;
}

proxy_buffering off sends each chunk as it arrives. Connection "" clears the header so nginx keeps the upstream connection alive. The app can also send X-Accel-Buffering: no in its response to turn buffering off for that one response. Also skip gzip for the stream, or events wait for the compressor. See gzip and caching headers.

Step 4: What Caddy does#

output
example.com {
    reverse_proxy 127.0.0.1:3000
}

Caddy’s reverse_proxy detects an upgrade request and proxies the websocket with no extra lines. Idle connections are not cut by a short default read timeout. For SSE you may want flush_interval -1 inside reverse_proxy so events are flushed immediately. See Caddy from scratch for the base file.

Check it worked#

Test the handshake with curl (the key is any 16 byte base64 value):

bash
curl -i -N \
  -H 'Connection: Upgrade' -H 'Upgrade: websocket' \
  -H 'Sec-WebSocket-Version: 13' \
  -H 'Sec-WebSocket-Key: SGVsbG8sIHdvcmxkIQ==' \
  https://example.com/socket/

A working setup prints HTTP/1.1 101 Switching Protocols. Without the nginx lines you get a 400 or 426. For SSE, curl -N https://example.com/events should print events as they happen, not in bursts.

Edge cases and gotchas#

  • Load balancers need affinity. Socket.IO style libraries may make several HTTP requests before upgrading, so across several backends they need sticky sessions. See load balancing across two backends.
  • A CDN or outer proxy has its own timeout. If another proxy sits in front of nginx, its idle timeout can close sockets even when nginx allows an hour.
  • proxy_read_timeout counts silence, not total time. Any data from the app resets it, which is why pings work.
  • Origin checks fail behind a proxy. If the app compares Origin to Host, pass the real host with proxy_set_header Host $host.
  • Rate limits and websockets. A limit_req on the socket path counts only the handshake. A limit_conn counts the open sockets, so set it high enough.
  • TLS terminates at nginx. The browser uses wss://, and the app sees ws:// on localhost. Pass X-Forwarded-Proto if the app cares.
  • Long sockets block clean reloads. Old workers wait for them, so a restart is the faster way to cut over when you must.

Troubleshooting#

SymptomLikely causeFix
Browser: WebSocket connection to 'wss://example.com/socket/' failedMissing Upgrade headersAdd the three lines and the map block
400 Bad Request from the app on the handshakeConnection header droppedAdd proxy_set_header Connection $connection_upgrade;
426 Upgrade RequiredApp got HTTP 1.0 without UpgradeSet proxy_http_version 1.1;
502 Bad GatewayApp not running, or crashed on the handshakeCheck the app, read error.log
connect() failed (111: Connection refused) while connecting to upstreamWrong port in proxy_passFix the port, see fix 502
Socket closes after 60 seconds idleDefault proxy_read_timeoutRaise it, add app level pings
upstream timed out (110: Connection timed out) while reading response header from upstreamTimeout on a slow handshake or silent streamRaise the timeout for that location
SSE events arrive in burstsBuffering or gzip on the streamproxy_buffering off;, no gzip

Quick reference#

nginx
map $http_upgrade $connection_upgrade { default upgrade; '' close; }

location /socket/ {
    proxy_pass http://127.0.0.1:3000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection $connection_upgrade;
    proxy_read_timeout 3600s;
}
bash
sudo nginx -t && sudo systemctl reload nginx
sudo tail -n 50 /var/log/nginx/error.log

Next#

With several app copies behind the proxy, continue with load balancing across two backends.

Check what you learned4 questions
1Which two request headers does nginx need to forward for a websocket handshake?
2Why is proxy_http_version 1.1; needed?
3A websocket drops after exactly a minute of silence. Which setting do you raise?
4Server-sent events arrive in big delayed chunks through nginx. What is the likely fix?

Frequently asked questions

How do I proxy websockets with nginx?

In the location, set proxy_http_version 1.1; and pass proxy_set_header Upgrade $http_upgrade; and proxy_set_header Connection $connection_upgrade; using a map block for the connection value.

Why does my websocket disconnect after 60 seconds?

nginx closes a proxied connection when nothing is read from the app for proxy_read_timeout, which defaults to 60 seconds. Raise it for the websocket location or send pings from the app.

Does Caddy need special config for websockets?

No. reverse_proxy detects the upgrade and handles websocket connections without extra lines.

How do I proxy server-sent events through nginx?

Set proxy_buffering off; for the stream location, use HTTP 1.1 to the app and a long proxy_read_timeout. Otherwise nginx holds events back until a buffer fills.

Sources

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios