[nginx] WebSocket Proxy

​ Function: Convert the connection between client and server from HTTP/1.1 to WebSocket
​ However, it is worth noting that: "Upgrade" is a hop-by-hop (hop-by-hop) header, which cannot be passed from the client to the proxy server. Using a forward proxy, clients can use the CONNECT method to circumvent this problem. However, using a reverse proxy doesn't work because the client doesn't know about the proxy server and requires special handling on the proxy server.
​ Starting from version 1.3.13, nginx implements a special mode of operation, if the proxied server returns a response with code 101 (exchange protocol), and the client requests protocol switching through the "Upgrade" header in the request , a tunnel is allowed between the client and the proxied server.

As mentioned above, "Upgrade" and "Connection" are not passed from the client to the proxy server, so in order for the proxy server to know the client's intent to switch protocol to WebSocket, these headers must be passed explicitly:

location /chat/ {
    proxy_pass http://backend;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
}

A more complex example, where the value of the "Connection" header field in a request to a proxy server depends on the presence of the "Upgrade" field in the client's 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, if the proxy server does not transmit any data for 60 seconds, the connection will be closed. This timeout can be increased with the proxy_read_timeout directive. Alternatively, the proxy server can be configured to periodically send WebSocket ping frames to reset the timeout and check that the connection is still alive.

nginx proxy ws and wss, with full configuration file + WebSocket online test tool: http://wstool.js.org/

Proxy ws

#user  nobody;
worker_processes 4;

events {
     worker_connections 1024;
}

http {
    map $http_upgrade $connection_upgrade{
            default upgrade;
            `` close;
    }

    server{
     
        listen 8020;
        location / {
                proxy_pass http://192.168.2.135:5001;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "Upgrade";
        }
    } 

}


Use ws://ip:8020 when connecting

Guess you like

Origin blog.csdn.net/weixin_35804181/article/details/130385410