How to configure WebSocket connections in nginx?

To set up Nginx to support WebSocket connections, the following steps need to be taken:

  1. Open the configuration file of Nginx (usually located at /etc/nginx/nginx.conf).
  2. Add the following configuration in the http section:
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://your_websocket_server;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}
  1. In the map directive, we define a variable $connection_upgrade, whose value depends on the Upgrade field in the request header. If the Upgrade field exists and is not empty, set the value to “upgrade”; otherwise, set it to “close”.
  2. In the server block, we listen on port 80 and specify the server name. The location block is used to handle all requests, proxying them to your WebSocket server. The proxy_http_version directive sets the HTTP version to 1.1, and the proxy_set_header directive sets the Upgrade and Connection request header fields to support WebSocket connections.
  1. – Please provide me with the URL for your WebSocket server.
  2. Save and close the configuration file.
  3. Check the syntax of nginx configuration.
  4. Restart the nginx service using systemctl.

After completing the above steps, Nginx will correctly proxy WebSocket connections. Make sure your WebSocket server is running smoothly and Nginx can access it.

bannerAds