Nginx配置WebSocket
2025/2/12...小于 1 分钟
Nginx 共同配置 Http 和 WebSocket
WebSocket 协议不是超文本传输协议。
尽管 WebSocket 协议确实使用 HTTP 请求启动了一个新连接,但它会迅速将连接升级为完整的 WebSocket (这需要在初始请求中包含Connection: upgrade头,而不是Connection: keep-alive)。
这里举个例子瞬间就能明白,我们使用 curl 命令,请求 WebSocket 服务需要如下命令:
curl 'http://localhost:8094/websocket/15' -H 'Upgrade: websocket' -H 'Connection: Upgrade' -H 'Sec-WebSocket-Version: 13' -H 'Sec-webSocket-Key: eeZn6lg/rOu8QbKwltqHDA==' --verbose
注意这里添加了两个头:
- Upgrade: websocket
- Connection: Upgrade
所以,在 Nginx 配置的时候,先对请求升级
map $http_upgrade $connection_upgrade {
default keep-alive; #默认为keep-alive 可以支持一般http请求
'websocket' upgrade; #如果为websocket 则n为upgrade可升级的。
}
然后再对nginx代理的地址进行配
location ^~ /shared_java/ {
proxy_redirect off;
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 Upgrade $http_upgrade;#此处配置 上面定义的变量
proxy_set_header Connection $connection_upgrade;
proxy_pass http://127.0.0.1:8094/;
}
参考链接: 自动配置 Nginx 辅助站点