Nginx代理websocket:升级为websocket后是否需要关闭与后端的连接?

Ant*_*bbs 5 nginx websocket

基于我在 nginx 网站 https://www.nginx.com/blog/websocket-nginx/上读到的内容

他们给出的示例将关闭与后端的所有连接。这并不是我们真正想要的代理设置,强制在每个新客户端上重新打开与后端的连接。

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是升级到websocket后是否需要关闭连接呢?

我们不能更改地图以使其保持与后端的“保持活动”连接吗?(对于所有非 websocket 请求)

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

作为测试环境中的唯一用户,它似乎没有产生任何问题,但在生产中会是一样的吗?

Mic*_*ton 1

map不会导致 websocket 连接关闭。

它实际上做的是检查Upgrade:请求标头是否包含任何值。如果是,则返回upgrade,然后将其作为 header 传递给上游Connection: upgrade

close仅当Upgrade:请求标头丢失时才返回。这种情况在正常操作中不应发生,但如果确实发生,那么您无论如何都无法可靠(或根本)建立与浏览器的 Websocket 连接。

  • “只有当 Upgrade: 请求标头丢失时,它才会返回 close。”但这就是任何经典连接(不是 websocket)上发生的情况。在启用 websocket 之前,我有一行 `proxy_set_header Connection ''` 来防止客户端“关闭”终止与后端的 keepalive。 (2认同)