Nginx WebSocket Proxy Configuration

Configure Nginx to proxy WebSocket connections with proper HTTP upgrade headers. Includes timeout tuning, connection persistence, and SSL WSS handling.

Proxy

Detailed Explanation

WebSocket connections require special handling in Nginx because they use the HTTP Upgrade mechanism to switch from a standard HTTP request into a persistent, bidirectional communication channel.

Basic WebSocket Proxy

The key requirement is passing the Upgrade and Connection headers from the client through to the backend server:

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 "upgrade";
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
}

Why HTTP/1.1 Is Required

WebSocket connections rely on the HTTP/1.1 Upgrade mechanism to switch protocols. By default, Nginx uses HTTP/1.0 for upstream connections, which does not support connection upgrades. The proxy_http_version 1.1 directive is therefore mandatory for WebSocket proxying to function correctly.

Timeout Configuration

WebSocket connections are inherently long-lived, but Nginx closes idle connections after 60 seconds by default. Increase the read and send timeouts to prevent premature disconnections of active WebSocket sessions:

proxy_read_timeout 3600s;
proxy_send_timeout 3600s;

Alternatively, implement application-level ping/pong frames at regular intervals to keep the connection active within the default timeout window.

Handling Both HTTP and WebSocket Traffic

Many applications serve both regular HTTP and WebSocket traffic on the same port. Use a map directive to conditionally set the Connection header based on whether the request includes an Upgrade header:

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

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

Load Balancing WebSockets

When load balancing WebSocket connections across multiple backends, use ip_hash to ensure a client always connects to the same backend server. This sticky session behavior is important because WebSocket state is typically held in memory on a specific server instance and is not shared across the cluster.

SSL WebSockets (WSS)

For secure WebSocket connections, terminate SSL at the Nginx level and proxy to an unencrypted backend internally. The client connects via wss:// to Nginx, which handles the TLS decryption and forwards the traffic as plain ws:// to the backend, simplifying certificate management.

Use Case

You are deploying a real-time chat application or live notification system that uses WebSocket connections and needs Nginx to properly proxy the upgraded connections to your backend.

Try It — Nginx Config Generator

Open full tool