Many WebSocket examples hardcode proxy_set_header Connection "upgrade";. That works for the socket, but every normal request through the same location then also tells the backend to upgrade.
The nginx docs use a map instead, in the http block:
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
location / {
proxy_pass http://127.0.0.1:8081;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
}
}
When the client sends an Upgrade header, $connection_upgrade becomes upgrade and the WebSocket handshake goes through. A request without one gets close. A test backend that echoes the headers shows the difference: a plain curl arrives with conn=close, and one with Upgrade: websocket arrives with conn=upgrade.
That matters for apps like Home Assistant or code editors in the browser that serve their pages and their socket from the same path. I like that one location then handles both.
The proxy_http_version 1.1 line is required, since the upgrade mechanism does not exist in HTTP/1.0, which nginx speaks to backends by default. And the map must sit in the http context, not inside a server block, or nginx -t refuses it.
Further reading: nginx WebSocket proxying, ngx_http_map_module
Going deeper: Guide: fix a 502 Bad Gateway in Nginx Proxy Manager, with a checklist that finds the cause