官網解讀-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幀來重置超時並檢查連接是否仍然有效。

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