官网解读-WebSocket proxying

http协议升级机制:https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Protocol_upgrade_mechanism

To turn a connection between a client and server from HTTP/1.1 into WebSocket, the protocol switchmechanism available in HTTP/1.1 is used.

要将客户端到代理端的连接协议从http转换为websocket,需要使用HTTP1.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. With forward proxying, clients may use the CONNECT method to circumvent this issue. 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.

然而,有一个微妙之处,由于'Upgrade'是一个hop-by-hop头,他不能从客户端传输到代理端,通过(翻译不一定正确)正向代理,客户端可以通过connect方法绕过这个问题,然而,这个不适用于反向代理,由于客户端不知道任何一台代理服务器,更不知道代理服务器需要怎么样的特殊处理。

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版本以来,如果代理服务器返回一个带有101响应,并且客户端通过'Upgrade'头请求协议转换,nginx便可实现在客户端与代理服务器之间建立一条隧道的特殊操作模式。

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:

如上所述,'hop-by-hop'头包含不能从客户端传输到代理服务端的'Upgrade'和'Connetction'头,因此,为了让代理服务器知道客户端转换协议的意图,这些头需要显示传输。

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:

一个更加复杂的例子是,想代理服务器发出请求时,'Connection'字段的值取决于请求头中是否含有'Upgrade'字段。

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. 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 ping帧来重置超时并检查连接是否仍然有效。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章