解析Nginx WebSocket代理配置

1.场景说明
1.1代理服务器nginx192.168.1.8,业务服务器nginx172.16.88.21
1.2websocket代理配置说明

2.nginx配置

2.1业务服务器nginx配置

server {
    listen 8080
    location /ws/ {
        proxy_pass http://wsserver/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_read_timeout 600s;
              
    }
}

2.2代理服务器nginx配置

upstream wsserver {
    server 172.16.88.21:8080;  # 替换为你的WebSocket服务器地址和端口
}

server {
    listen 8080;

    location /ws/ {
        proxy_pass http://wsserver/ws/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";  # 修正此行,确保正确处理连接升级
        proxy_read_timeout 600s;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

}

3.代理中proxy_pass http://wsserver/ws/; 加/ws和不加有啥区别

在proxy_pass指令中,使用http://wsserver/ws/和不使用/ws/之间的区别在于请求路径的处理方式。具体来说:

#不加 /ws/ 的情况
location /ws/ {
    proxy_pass http://wsserver/;
    ...
}

行为:
当客户端请求路径为 /ws/somepath 时,代理服务器会将请求转发到上游服务器的 /somepath 路径。
实际上,上游服务器接收到的请求路径会是 /somepath。

例如:
客户端请求:http://your-proxy-server/ws/somepath
上游服务器收到的请求:http://wsserver/somepath



#加 /ws/ 的情况
location /ws/ {
    proxy_pass http://wsserver/ws/;
    ...
}
行为: 当客户端请求路径为
/ws/somepath 时,代理服务器会将请求转发到上游服务器的 /ws/somepath 路径。 实际上,上游服务器接收到的请求路径会是 /ws/somepath。 例如: 客户端请求:http://your-proxy-server/ws/somepath 上游服务器收到的请求:http://wsserver/ws/somepath

4.区别总结

不加 /ws/: 上游服务器接收到的路径是去除了 /ws/ 前缀的路径。
加 /ws/: 上游服务器接收到的路径是保留了 /ws/ 前缀的路径。
选择哪种方式取决于上游服务器的配置。如果上游服务器期望接收到的路径包含 /ws/ 前缀,那么你应该在 proxy_pass 中加上 /ws/;如果上游服务器期望接收到的路径不包含 /ws/ 前缀,那么就不应该在 proxy_pass 中加上 /ws/

 

posted @ 2024-06-28 12:32  Leonardo-li  阅读(17)  评论(0编辑  收藏  举报