Nginx WebSocket Proxy Configuration

WebSockets start as an HTTP request that asks to be upgraded. Nginx does not pass the Upgrade header on by default, so a plain proxy_pass drops the connection with a 400 or 101 failure.

The required headers

Use HTTP/1.1 to the backend and forward Upgrade and Connection.

map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}
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_read_timeout 3600s;
}

Timeouts

proxy_read_timeout defaults to 60 seconds of silence and then closes the socket. Raise it, or have the app send periodic pings.

Open the Reverse proxy generator

Frequently asked questions

Why does my WebSocket disconnect after 60 seconds?

That is proxy_read_timeout. Increase it or send ping frames more often than the timeout.

Does the map block go in server or http?

The http context. map is not valid inside a server block.

Guides