WebSocket proxyingWebSocket代理
To turn a connection between a client and server from HTTP/1.1 into WebSocket, the protocol switch mechanism available in HTTP/1.1 is used.要将客户端和服务器之间的连接从HTTP/1.1转换为WebSocket,需要使用HTTP/1.1中可用的协议切换机制。
There is one subtlety however: since the “Upgrade” is a hop-by-hop header, it is not passed from a client to proxied server. 然而,有一个微妙之处:因为“升级”是一个hop-by-hop的头,所以它不会从客户端传递到代理服务器。With forward proxying, clients may use the 使用前向代理,客户端可以使用CONNECT
method to circumvent this issue. CONNECT
方法来避免此问题。This does not work with reverse proxying however, since clients are not aware of any proxy servers, and special processing on a proxy server is required.但是,这不适用于反向代理,因为客户端不知道任何代理服务器,并且需要在代理服务器上进行特殊处理。
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.自1.3.13版以来,nginx实施了特殊的操作模式,如果代理服务器返回代码为101(交换协议)的响应,并且客户端通过请求中的“升级”头请求协议切换,则允许在客户端和代理服务器之间建立隧道。
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:如上所述,包括“升级”和“连接”在内的逐跳标头不会从客户端传递到代理服务器,因此,为了让代理服务器了解客户端将协议切换到WebSocket的意图,必须显式传递这些标头:
location /chat/ {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
A more sophisticated example in which a value of the “Connection” header field in a request to the proxied server depends on the presence of the “Upgrade” field in the client request header:一个更复杂的示例,其中到代理服务器的请求中的“连接”标头字段的值取决于客户端请求标头中是否存在“升级”字段:
http { map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { ... location /chat/ { proxy_pass http://backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; } }
By default, the connection will be closed if the proxied server does not transmit any data within 60 seconds. 默认情况下,如果代理服务器在60秒内未传输任何数据,则连接将关闭。This timeout can be increased with the proxy_read_timeout directive. 此超时可以通过proxy_read_timeout指令增加。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.或者,可以将代理服务器配置为定期发送WebSocket ping帧,以重置超时并检查连接是否仍处于活动状态。