skip to content
声控烤箱 | KazooTTT 博客

配置nginx以成功代理websocket

Updated:

配置 nginx 以成功代理 websocket

在使用 socket.io 的时候遇到这样一个问题:websocket 接收的消息的顺序错位了,然后看了一下浏览器的 console 的报错,提示连接到 ws 失败,然后在浏览器的开发者工具的网络中看了一下 ws 对应的消息里面报错:Error during WebSocket handshake: Unexpected response code: 200

查了一下发现是 nginx 没有配置的问题。

相关的类似的问题:

https://github.com/websockets/ws/issues/979

nginx 官方文档提到的解决方法:

WebSocket proxying

需要注意的是:

location /chat/socket.io {
proxy_pass <http://backend>;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}

这里的 backend 就是 ip 地址或者域名,不需要加后缀/chat/socket.io。

感谢阅读到这里,期待收到更多的反馈
欢迎关注公众号
kazoottt
公众号二维码