基于$arg_name(URL查询字符串参数)的反向代理websockets

Reverse proxying websockets based on $arg_name (URL Query String Parameter)

nginx 使用我的 websocket 服务器使用以下方法:

server {
    listen 80;
    server_name streams.domain.com;
    location / {
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_pass http://192.168.1.52:80;
    }
}

但是,我需要根据查询字符串参数更改目标。我将其更改为以下内容:

server {
    listen 80;
    server_name streams.domain.com;
    location / {
        if ( $arg_serverId = 1562182 ) { 
            return 101 http://192.168.1.52:80; 
        }
    }
}

现在我得到错误 Error during WebSocket handshake: 'Upgrade' header is missing

所以我尝试使用 add_header 但使用下面的配置我只得到 ERR_CONNECTION_TIMED_OUT:

server {
    listen 80;
    server_name streams.domain.com;
    location / {
        if ( $arg_serverId = 1562182 ) { 
            add_header 'Upgrade' $http_upgrade;
            add_header 'Connection' $connection_upgrade;
            return 101 http://192.168.1.52:80; 
        }
    }
}

那么如何使用 $arg_ 条件并通过 websockets 所需的升级 headers?

我最终让它与 map 一起工作。对于像 http://stream.domain.com?serverId=1001 这样的 URL,下面的效果很好:

http {
    map $arg_serverId $streamdestination {
        1001 http://192.168.1.52:80; 
        1002 http://192.168.1.51:80; 
        1003 http://192.168.1.50:80; 
    }
    server {
        listen 80;
        server_name streams.domain.com;
        location / {
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_pass $streamdestination;
        }
    }
}