背景:搭建了一个ws流的视频代理,一个代理支撑不住过多视频播放,所以Nginx搭建负载均衡监听端口分发到代理。
http {
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
upstream websocket {
server 127.0.0.1:59002;
server 127.0.0.1:59003;
}
server {
listen 59001;
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;
}
}
}
WebSocket 协议与 HTTP 协议不同,但 WebSocket 握手与 HTTP 兼容,使用 HTTP 升级工具将连接从 HTTP 升级到 WebSocket。这使得 WebSocket 应用程序能够更轻松地适应现有的基础结构。例如,WebSocket 应用程序可以使用标准 HTTP 端口 80 和 443,从而允许使用现有的防火墙规则。
最重要的就是在反向代理的配置中增加了如下两行,然后 HTTP 升级到 WebSocket。其它的部分和普通的HTTP反向代理没有任何差别。
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
注意:
upstream websocket和proxy_pass http://websocket的websocket命名要一样。
参考链接:
https://www.nginx.com/blog/websocket-nginx/
https://www.cnblogs.com/hahaha111122222/p/11996951.html