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.
- Updated Nov 27, 2026
- Markdown
Proxy a websocket and a server-sent events stream through nginx, and recognise the 400, 502 and dropped-connection symptoms.
- 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):
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#
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.1allows the upgrade.- The two
UpgradeandConnectionlines pass the handshake on. Hostand the forwarded headers are the same as in nginx reverse proxy for a Node app. Many apps checkOriginagainst the host, so keep them.proxy_read_timeout 3600slets 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:
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#
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):
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_timeoutcounts 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
OrigintoHost, pass the real host withproxy_set_header Host $host. - Rate limits and websockets. A
limit_reqon the socket path counts only the handshake. Alimit_conncounts the open sockets, so set it high enough. - TLS terminates at nginx. The browser uses
wss://, and the app seesws://on localhost. PassX-Forwarded-Protoif 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#
| Symptom | Likely cause | Fix |
|---|---|---|
Browser: WebSocket connection to 'wss://example.com/socket/' failed | Missing Upgrade headers | Add the three lines and the map block |
400 Bad Request from the app on the handshake | Connection header dropped | Add proxy_set_header Connection $connection_upgrade; |
426 Upgrade Required | App got HTTP 1.0 without Upgrade | Set proxy_http_version 1.1; |
502 Bad Gateway | App not running, or crashed on the handshake | Check the app, read error.log |
connect() failed (111: Connection refused) while connecting to upstream | Wrong port in proxy_pass | Fix the port, see fix 502 |
| Socket closes after 60 seconds idle | Default proxy_read_timeout | Raise it, add app level pings |
upstream timed out (110: Connection timed out) while reading response header from upstream | Timeout on a slow handshake or silent stream | Raise the timeout for that location |
| SSE events arrive in bursts | Buffering or gzip on the stream | proxy_buffering off;, no gzip |
Quick reference#
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;
}sudo nginx -t && sudo systemctl reload nginx
sudo tail -n 50 /var/log/nginx/error.logRelated lessons#
- Nginx reverse proxy for a Node app: the base proxy config.
- Fix 504 gateway timeout: when a timeout cuts requests.
- Fix 502 Bad Gateway: when nginx cannot reach the app.
- Deploy a Next.js app on a VPS with Docker: an app that often uses streaming responses.
Next#
With several app copies behind the proxy, continue with load balancing across two backends.
Check what you learned
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
Keep going: guides and tutorials
- Self-Hosted Static Site Hosting: Deploy a Folder With Levelrail Self-hosted static site hosting from a plain folder: one deploy command, _redirects, _headers and a custom 404 honored, plus a one command rollback.
- Deploy Next.js on a VPS With Docker, Git Push and HTTPS Deploy a Next.js app to your own VPS with Docker, a health check, HTTPS and rollback. Includes the NEXT_PUBLIC build trap that leaves variables empty.