nginx支持websocket连接

nginx 要支持 websocket 是很简单的,只需要增加 3 个配置就行。
表明是 websocket 连接进入的时候,进行一个连接升级将 http 连接变成 websocket 的连接。
前端就可以通过ws://xxxxx进行 socket 长连接了。

1
2
3
4
5
6
7
location / {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_read_timeout 300s;
...
}

注意:

  1. 2 个 proxy_set_header 的设置需要放在 location 中,不要放在 server 中,否则的话不会生效。
  2. 使用nginx做websocket连接会有一个超时时间,默认是60s,即当60s内客户端和服务端没有消息通信会断开长连接。所以稍微设置长点超时时间,并在客户端定时发起心跳消息.