WebSocket 代理配置
Nginx原文地址:http://nginx.org/en/docs/http/websocket.html
Since version 1.3.13, nginx implements special mode of operation that allows setting up a tunnel between a client and proxied server if the proxied server returned a response with the code 101 (Switching Protocols), and the client asked for a protocol switch via the “Upgrade” header in a request.
As noted above, hop-by-hop headers including “Upgrade” and “Connection” are not passed from a client to proxied server, therefore in order for the proxied server to know about the client’s intention to switch a protocol to WebSocket, these headers have to be passed explicitly
大致意思就是说nginx从1.3.13版本开始支持websocket协议,主要是通过在配置中增加请求头信息:
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
By default, the connection will be closed if the proxied server does not transmit any data within 60 seconds. This timeout can be increased with the proxy_read_timeout directive. Alternatively, the proxied server can be configured to periodically send WebSocket ping frames to reset the timeout and check if the connection is still alive.
默认情况下,如果代理服务器在60秒内未传输任何数据,则连接将关闭。可以使用proxy_read_timeout指令来增加此超时时间
实例:
# Websocket服务
server {
listen 80;
server_name 8080.huang.com;
location / {
proxy_pass http://8080.huang.com:8080;
proxy_read_timeout 3600s;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
在线测试地址:
http://www.jsons.cn/websocket/
测试结果: