brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: a map on $http_upgrade lets one nginx location serve WebSockets and normal requests

Nginx
~/tips/tip-nginx-map-connection-upgrade

map $http_upgrade $connection_upgrade {

Sends Connection upgrade only when the client asks for it, and close otherwise.

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

More Nginx tips sudo certbot --nginx -d example.com -d www.example.com /data/nginx/custom/server_redirect.conf proxy_intercept_errors on; proxy_redirect http://localhost:3000/ /app/; sub_filter 'http://127.0.0.1:8081/' 'https://example.com/app/'; All Nginx tips (50) All topics

Link