Nginx proxy websocket: is it required to close the connection to backend after upgrading to a websocket

nginxwebsocket

Base on what I could read on nginx site
https://www.nginx.com/blog/websocket-nginx/

The exemple they give will close all connections to backend. This isn't really what we want on a proxy setup, forcing to reopen a connection to backend on each new client.

http {
    map $http_upgrade $connection_upgrade {
        default upgrade;
        '' close;
    }
 
    upstream websocket {
        server 192.168.100.10:8010;
    }
 
    server {
        listen 8020;
        location / {
            proxy_pass http://websocket;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection $connection_upgrade;
            proxy_set_header Host $host;
        }
    }
}

But is it required to close the connection after upgrading to a websocket?

can't we change the map so it maintains the 'keepalive' connection to the backend ? (for all non websocket requests)

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

Being the only user on a test environment it didn't seem to create any issues, but will it be the same in production?

Best Answer

This map does not cause websocket connections to close.

What it actually does is check whether the Upgrade: request header contains any value. If it does, then it returns upgrade, which is then passed upstream as the header Connection: upgrade.

It only returns close when the Upgrade: request header is missing. This should not happen in normal operation, but if it does happen, then you can't reliably (or at all) establish a websocket connection to the browser anyway.

Related Topic