SoFunction
Updated on 2025-03-04

Detailed explanation of Nginx configuration support WebSocket function

Nginx configuration supports WebSocket function

Just deployed a project that requires WebScoket implementation. However, when pointing to NG through the domain name, it was found that it could not be accessed through the domain name. After searching for information, it was found that it needed to add WebSocket forwarding configuration in Nginx.

1. Online general configuration

Most configurations are found online as follows

location /websocket/ {
        proxy_pass http://myserver;
 
        proxy_http_version 1.1;
        proxy_read_timeout 360s;   
        proxy_redirect off;   
        proxy_set_header Upgrade $http_upgrade; 
        proxy_set_header Connection "upgrade";    #Configure the connection as an upgrade connection        proxy_set_header Host $host:$server_port;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header REMOTE-HOST $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

Using the above connection, if all connections are only requested by the "ws" protocol, there is no problem

However, if you want to support http request and support ws requesting the above configuration, it will not work

2. Support both http and ws configuration

Through nginx officialWebSocket configurationKnow that you can customize variables.

Therefore, the configuration is as follows, so that both ws requests and http requests can be supported.

http {
 
   #Custom variable $connection_upgrade    map $http_upgrade $connection_upgrade { 
        default          keep-alive;  #The default is keep-alive and can support general http requests        'websocket'      upgrade;     #If it is a websocket, upgrade is upgradeable.    }
 
    server {
        ...
 
        location /chat/ {
            proxy_pass http://backend;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade; #Configure the variables defined above            proxy_set_header Connection $connection_upgrade;
        }
    }
}

In this configuration:

  • map $http_upgrade The $connection_upgrade block is used to set the value of the Connection header based on the value of the Upgrade header sent by the client.
  • proxy_pass Points to the backend address of the WebSocket service.
  • proxy_http_version 1.1 Specifies to use HTTP/1.1 to keep the connection open.
  • proxy_set_header Upgrade $http_upgrade and proxy_set_header Connection $connection_upgrade Make sure the correct header is sent to the backend so that it can recognize the WebSocket connection.

Make sure your Nginx version is 1.3 or higher to support WebSocket.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.