Skip to content

Proxy WebSocket connections through Nginx

Configure Nginx as a WebSocket reverse proxy so a browser connecting over wss:// reaches your backend and the connection stays open. You will forward the upgrade headers, switch the upstream to HTTP/1.1, raise the idle timeout, and confirm the handshake returns 101 Switching Protocols.

This guide shows you how to put Nginx in front of a WebSocket app, so a browser connecting over wss:// reaches your backend and stays connected. A WebSocket keeps a connection open in both directions, and it begins as an ordinary HTTP request that asks to switch protocols. Nginx does not pass that request along on its own, so the app connects, fails, and the console shows a 400 or a socket that dies seconds after it opens. The fix is short: speak HTTP/1.1 to your backend, forward the Upgrade and Connection headers, and raise the read timeout so an idle socket is not cut at 60 seconds. By the end you will have wss:// working through Nginx, plus a way to prove the handshake really returns 101 Switching Protocols.

What you’ll accomplish

  • Forward a browser wss:// connection through Nginx to a ws:// backend (Socket.IO, the ws library, Phoenix Channels, or any WebSocket server).
  • Terminate TLS at Nginx so the backend only ever speaks plain WebSocket.
  • Write the map block that computes the Connection header so normal HTTP requests keep their keep-alive.
  • Keep long-lived idle connections open instead of losing them at the default 60-second timeout.
  • Recognize each broken-handshake failure by its status code or log line.

Prerequisites

  • Nginx 1.18 or newer (the map directive and proxy_http_version have been stable for years).
  • A backend that speaks WebSocket on a known host and port — for example a Node process on 127.0.0.1:3000.
  • A TLS certificate for the public hostname if you are terminating wss:// at Nginx (a Let’s Encrypt cert is fine).
  • Shell access to edit the config and run nginx -t and systemctl reload nginx.

One non-negotiable detail: proxy_http_version must be 1.1. WebSocket upgrades do not exist in HTTP/1.0, and Nginx defaults the upstream protocol to 1.0. Leave it at the default and the handshake cannot succeed no matter what headers you set.

How it works

A WebSocket handshake is an HTTP GET carrying two special headers: Upgrade: websocket and Connection: Upgrade. The server that accepts it replies with status 101 Switching Protocols instead of the usual 200. After that 101, the bytes on the socket are no longer HTTP — both ends exchange WebSocket frames until one side closes. The connection is long-lived and bidirectional, which is exactly why a reverse proxy has to be told to stop treating it as a normal request/response pair.

Nginx sits in the middle. The browser opens wss://app.example.com/ws, Nginx terminates TLS, and Nginx must open a plain ws:// connection to the backend and copy the Upgrade and Connection headers across. If it forwards them, the backend returns 101, Nginx passes that 101 back to the browser (re-wrapped in TLS as wss), and from then on Nginx just pipes frames in both directions until close.

The subtlety is the Connection header. You cannot simply hardcode Connection: upgrade on every proxied request, because ordinary HTTP requests to the same server should keep Connection: keep-alive for connection reuse. The idiomatic solution is a map that reads the incoming Upgrade header and produces the right Connection value: upgrade when a WebSocket is requested, and an empty/close value otherwise. That computed variable is what you feed into proxy_set_header Connection.

Sequence diagram of a WebSocket upgrade travelling from a wss browser through Nginx TLS termination to a ws backend and back as 101 Switching Protocols, then a persistent bidirectional tunnel

Step-by-step

1. Define the map block in the http {} context. This belongs at the http level, not inside server or location. It reads $http_upgrade (the request’s Upgrade header) and sets $connection_upgrade. Put it in /etc/nginx/nginx.conf inside http {}, or in a snippet included from there:

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

The default upgrade; line means: if the request carried any Upgrade header, send Connection: upgrade. The second line means: if Upgrade was empty (a normal request), send Connection: close instead. This one block is what keeps regular traffic from being force-upgraded.

2. Configure the location that proxies the WebSocket endpoint. In your server {} block, point the WebSocket path at the backend and set the four headers that matter. Here is the minimal working set:

location /ws/ {
    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-Real-IP         $remote_addr;
    proxy_set_header X-Forwarded-For   $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
}

proxy_http_version 1.1 enables the upgrade path. The two Upgrade/Connection lines carry the handshake. Host and the X-Forwarded-* headers let the backend know the original host and that the client arrived over https, which many frameworks (Socket.IO, Phoenix) need to build correct URLs and to trust the connection as secure.

3. Raise the idle timeouts for long-lived sockets. Nginx closes an upstream connection after proxy_read_timeout seconds without data — default 60s. A chat socket or a dashboard that only pushes an update every few minutes will be torn down mid-session. Raise both the read and send timeouts inside the same location:

proxy_read_timeout 3600s;
proxy_send_timeout 3600s;

An hour is a reasonable ceiling for most apps; pick a value longer than your quietest expected gap between frames. If your application sends its own heartbeat/ping frames (Socket.IO does by default), those count as traffic and reset the timer, so a shorter value is often fine — but the default 60 is the single most common reason a connection “randomly” drops.

4. Terminate TLS in the same server block. The browser connects with wss://, so the server listens on 443 with your certificate. The backend stays plain ws:// behind it:

server {
    listen 443 ssl;
    server_name app.example.com;

    ssl_certificate     /etc/letsencrypt/live/app.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/app.example.com/privkey.pem;

    location /ws/ {
        # ... the proxy_pass + headers + timeouts from steps 2 and 3
    }
}

Because TLS ends at Nginx, proxy_pass uses http:// (not https://) to reach the backend. The X-Forwarded-Proto $scheme header is what tells the backend the original request was secure.

5. Test the config, then reload. Never skip nginx -t — a syntax slip here takes the site down on reload:

sudo nginx -t
sudo systemctl reload nginx

Expected output from the test:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

reload applies the change with zero dropped connections on existing workers.

6. Prove the handshake returns 101 with curl. You can drive a raw upgrade by hand and watch for 101 Switching Protocols:

curl --include --no-buffer \
  --header "Connection: Upgrade" \
  --header "Upgrade: websocket" \
  --header "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==" \
  --header "Sec-WebSocket-Version: 13" \
  https://app.example.com/ws/

A working proxy responds with the switch and then holds the connection open:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

If instead you get HTTP/1.1 400 Bad Request or a 426, the Upgrade/Connection headers are not reaching the backend — recheck step 2.

7. Confirm a real client round-trips with websocat. curl proves the handshake; websocat proves frames flow. Install it, then connect and type a message:

websocat wss://app.example.com/ws/

If the backend echoes or acknowledges, the tunnel is live. A connection that opens and immediately closes usually means the 101 was returned but something downstream (a timeout, a second proxy, or buffering) is interfering.

Validate it works

Open the app in a browser and look at the network panel in devtools. Filter to WS; the request to /ws/ should show status 101 and a green/open state, and the Messages tab should list frames going both directions as you interact. On the server, tail the access log — the upgraded request is logged with a 101:

sudo tail -f /var/log/nginx/access.log | grep ' 101 '

The real proof is duration. Leave the connection idle and watch that it survives past 60 seconds — if it does, your proxy_read_timeout change took effect. A message you send from the app should round-trip without a reconnect, and the connection count should stay stable rather than climbing as clients silently reconnect after drops.

Troubleshooting

  • 400 Bad Request or 426 Upgrade Required, handshake never completes. The Upgrade header is not being forwarded. Either proxy_http_version 1.1 is missing (Nginx is talking HTTP/1.0 upstream, where upgrades do not exist), or the proxy_set_header Upgrade $http_upgrade line is absent from this location. Note that proxy_set_header directives do not inherit into a location if that location defines any of its own — if you set headers elsewhere and none here, none apply. Put all four header lines directly in the WebSocket location.

  • Connection drops after exactly 60 seconds. That is the default proxy_read_timeout. Nginx saw no bytes for 60s and closed the upstream. Raise proxy_read_timeout (and proxy_send_timeout) as in step 3, or make the app emit a periodic ping so the socket is never idle that long. If it drops at a rounder number like 65 or 75 seconds, check whether a load balancer or cloud gateway in front of Nginx has its own idle timeout.

  • 502 Bad Gateway on the WebSocket path. The handshake headers are fine but nothing is listening at the proxy_pass address, or the backend rejected the connection. Confirm the backend is actually up on that host/port with ss -ltnp | grep 3000, and that proxy_pass points at the right port. This is a backend-reachability problem, not a WebSocket one — the same causes and log lines are covered in fixing nginx 502 Bad Gateway.

  • Normal pages break after adding the config. You hardcoded proxy_set_header Connection "upgrade"; instead of using the mapped variable. Every ordinary request now carries Connection: upgrade, which confuses keep-alive and breaks non-WebSocket responses. Revert to proxy_set_header Connection $connection_upgrade; and keep the map block from step 1 — that is the entire reason the map exists.

  • Handshake works but frames stall or arrive in bursts. Response buffering is holding frames. Add proxy_buffering off; to the WebSocket location so Nginx pipes frames through immediately instead of accumulating them. If Nginx sits behind another load balancer, also make sure that layer routes each client to the same backend — Socket.IO’s default long-polling upgrade needs sticky sessions, so enable ip_hash or a sticky cookie on the upstream, otherwise the polling and WebSocket phases can land on different backends.

When this is the wrong approach

Nginx as a WebSocket reverse proxy is the right tool for terminating TLS and routing realtime traffic to one or a few backends. It is the wrong tool once fan-out gets large. If you are pushing to tens of thousands of concurrent subscribers, a dedicated WebSocket gateway (a pub/sub layer, or a managed realtime service) will handle connection sharding and backpressure that a plain proxy will not. If your data is one-directional — the server pushes, the client never sends — Server-Sent Events over plain HTTP are simpler to proxy and reconnect than WebSocket, and there is no upgrade dance at all. And if a CDN or edge platform already terminates and proxies WebSocket for you, adding your own Nginx hop in front usually just doubles the idle-timeout problem; configure the timeouts at the edge instead, as covered in WebSockets and SSE behind Cloudflare.

The authoritative reference for these directives is the Nginx WebSocket proxying documentation, which is the source of the map/$connection_upgrade pattern used here.

If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.