# 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.

URL: https://levelrail.com/learn/web-servers/websockets-through-a-proxy/
Updated: 2026-11-27

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](https://levelrail.com/learn/glossary/#tls)) in [nginx](https://levelrail.com/learn/glossary/#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](https://levelrail.com/learn/glossary/#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](https://levelrail.com/learn/web-servers/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](https://levelrail.com/learn/web-servers/gzip-and-caching-headers/)).

## Step 4: What Caddy does

```text
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](https://levelrail.com/learn/web-servers/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](https://levelrail.com/learn/web-servers/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

| 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](https://levelrail.com/learn/deploy-operate/fix-502-bad-gateway/)) |
| 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

```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
```

## Related lessons

- [Nginx reverse proxy for a Node app](https://levelrail.com/learn/web-servers/nginx-reverse-proxy-for-a-node-app/)): the base proxy config.
- [Fix 504 gateway timeout](https://levelrail.com/learn/troubleshooting/fix-504-gateway-timeout/)): when a timeout cuts requests.
- [Fix 502 Bad Gateway](https://levelrail.com/learn/deploy-operate/fix-502-bad-gateway/)): when nginx cannot reach the app.
- [Deploy a Next.js app on a VPS with Docker](https://levelrail.com/blog/deploy-nextjs-on-vps-docker/)): an app that often uses streaming responses.

## Next

With several app copies behind the proxy, continue with [load balancing across two backends](https://levelrail.com/learn/web-servers/load-balancing-across-two-backends/)).

## 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

- [Nginx docs, websocket proxying](https://nginx.org/en/docs/http/websocket.html)
- [Nginx docs, ngx_http_proxy_module](https://nginx.org/en/docs/http/ngx_http_proxy_module.html)
- [Caddy docs, reverse_proxy](https://caddyserver.com/docs/caddyfile/directives/reverse_proxy)
