SoFunction
Updated on 2025-04-14

Detailed tutorial on configuring WebSocket in Nginx

Introduction

WebSocket is a protocol for full duplex communication on a single TCP connection. WebSocket makes data exchange between clients and servers easier, allowing the server to actively push data to clients. In the WebSocket API, the browser and the server only need to complete a handshake, and a persistent connection can be created directly between the two and two-way data transmission.

As a high-performance HTTP and reverse proxy server, Nginx needs to be configured to support WebSocket connections and communications when handling the WebSocket protocol. This article will explain in detail how to configure WebSocket in Nginx.

Preparation

Before you start configuring, make sure that Nginx is already installed in your environment and that Nginx version is at least 1.3.13, as this is the version where Nginx starts supporting the WebSocket protocol.

Check Nginx version

nginx -v

If the version is lower than 1.3.13, you need to update or recompile Nginx to include WebSocket support.

Configure Nginx to support WebSocket

Modify Nginx configuration file

Open your Nginx configuration file, usually located in the /etc/nginx/​​ or /etc/nginx//​​ directory. Find the server block you want to configure WebSocket and add the following configuration:

server {
    listen 80;
    server_name your_domain.com;
 
    location /ws/ {
        proxy_pass http://backend_server;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
    }
}

Explain configuration items

  • proxy_pass http://backend_server;​​: Specify the address of the backend WebSocket service.
  • proxy_http_version 1.1;​​: Set the HTTP version used by the proxy to 1.1, which is required for WebSocket.
  • proxy_set_header Upgrade $http_upgrade;​​: Passes Upgrade header information to the backend server, which tells the server client that wants to upgrade to the WebSocket protocol.
  • proxy_set_header Connection "upgrade";​​: Passes Connection header information to control or specify the properties of the current connection or message body.
  • proxy_set_header Host $host;​​: Pass the host header information in the original request to the backend server.

Test configuration

After modifying the configuration file, first test whether the configuration is correct:

nginx -t

If there is no error, restart Nginx to make the configuration take effect:

sudo systemctl restart nginx

or

sudo service nginx restart

Testing WebSocket Connection

To verify that Nginx has successfully configured WebSocket, you can write a simple WebSocket client and server to test it. Here is a basic example:

WebSocket Server ()

const WebSocket = require('ws');
const wss = new ({ port: 8080 });
 
('connection', ws => {
    ('Client connected');
    ('message', message => {
        ('Received:', message);
        (`Echo: ${message}`);
    });
});

WebSocket Client (HTML + JavaScript)

<!DOCTYPE html>
<html>
<head>
    <title>WebSocket Test</title>
</head>
<body>
    <script>
        const socket = new WebSocket('ws://your_domain.com/ws/');
 
         = () => {
            ('Connected to the WebSocket server.');
            ('Hello Server!');
        };
 
         = event => {
            ('Message from server:', );
        };
 
         = () => {
            ('Disconnected from the WebSocket server.');
        };
    </script>
</body>
</html>

Run the test

Start the WebSocket server.

Open a browser and access the HTML page containing the WebSocket client code.

Check the console output in the browser's developer tools to confirm whether the connection and messaging with the WebSocket server are normal.

If you encounter any problems, it is recommended to check Nginx logs and the logs of the WebSocket server to quickly locate the problem. In many modern web applications, WebSocket is widely used to implement real-time communication, such as online chat, real-time data update, etc. As a high-performance HTTP and reverse proxy server, Nginx can support these applications by configuring to support the WebSocket protocol.

Here is an example of an Nginx configuration file that shows how to set up Nginx to support WebSocket connections:

Nginx configuration file example

# Define an http blockhttp {
    # Set log format    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';
 
    access_log /var/log/nginx/ main;
    error_log /var/log/nginx/;
 
    # Include other configuration files    include       /etc/nginx/;
    default_type  application/octet-stream;
 
    # Set the maximum size of the send file    client_max_body_size 10M;
 
    # Define a server block    server {
        listen 80;  # Listen to port 80        server_name ;  # Your domain name 
        # Configure static file directory        location / {
            root /usr/share/nginx/html;
            index  ;
        }
 
        # Configure WebSocket Agent        location /ws/ {
            proxy_pass http://localhost:3000;  # Backend WebSocket service address            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-NginX-Proxy true;
 
            # Timeout time (unit: seconds)            proxy_read_timeout 86400s;
            proxy_send_timeout 86400s;
        }
    }
}

explain

  • listen 80;: This line specifies the Nginx listening port 80.
  • server_name ​​​;: Specify the domain name of the server.
  • location /{ ... }: This part configures the processing method of static files.
  • location /ws/ { ... }: This part is key, the proxy configured with WebSocket:
  • proxy_pass ​http://localhost:3000​;: Forward the request to the WebSocket service on the backend. The localhost:3000 here should be replaced with your actual WebSocket service address.
  • proxy_http_version 1.1;: Set HTTP version to 1.1, because WebSocket requires HTTP 1.1.
  • proxy_set_header Upgrade $http_upgrade; and proxy_set_header Connection "upgrade";: These two lines are the key, telling Nginx that this is a WebSocket connection.
  • proxy_set_header Host $host; etc.: Set some necessary header information to help the backend service handle requests correctly.
  • proxy_read_timeout 86400s; and proxy_send_timeout 86400s;: Set the read and write timeout to 24 hours to ensure that long-term connections will not be interrupted by Nginx.

Test configuration

After modifying the Nginx configuration file, you can use the following command to test whether the configuration is correct:

sudo nginx -t

If the test passes, Nginx can be reloaded to apply the new configuration:

sudo systemctl reload nginx

In this way, Nginx has configured support for WebSocket. Hope this example helps you! If you have any questions or need further assistance, feel free to let me know. sure! Configuring WebSocket support in Nginx allows Nginx to serve as a reverse proxy server to forward WebSocket requests to the backend WebSocket service. Here is a detailed step and example configuration to help you configure WebSocket in Nginx.

1. Ensure that Nginx version supports WebSocket

First, make sure your Nginx version supports WebSocket. Since Nginx version 1.3.13, Nginx has supported the WebSocket protocol. You can check the Nginx version by:

nginx -v

2. Install Nginx (if not already installed)

If you haven't installed Nginx, you can install it through the following command (taking Ubuntu as an example):

sudo apt update
sudo apt install nginx

3. Configure Nginx to support WebSocket

Edit Nginx's configuration file, usually located in /etc/nginx/ or /etc/nginx/sites-available/default. You can add WebSocket-related configurations in the server block.

Here is a sample configuration:

http {
    #Other HTTP configurations 
    upstream websocket_backend {
        server 127.0.0.1:8080;  # Address and port of WebSocket service    }
 
    server {
        listen 80;
        server_name your_domain.com;
 
        location /ws/ {
            proxy_pass http://websocket_backend;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_set_header Host $host;
 
            # Optional: Set the timeout time            proxy_read_timeout 86400s;
            proxy_send_timeout 86400s;
        }
 
        #Other location configurations        location / {
            # For example, static file service            root /var/www/html;
            index  ;
        }
    }
}

4. Explain the configuration

  • upstream websocket_backend​: Defines a cluster of backend WebSocket services. Here we assume that the WebSocket service is running at 127.0.0.1:8080.
  • listen 80;​​: Listen to port 80.
  • server_name your_domain.com;​: Specify the server name and replace it with your actual domain name.
  • location /ws/​​: Defines the path to handle WebSocket requests.
  • proxy_pass http://websocket_backend;​​: Forward the request to the defined backend WebSocket service.
  • proxy_http_version 1.1;​​: Use HTTP/1.1 version because the WebSocket protocol is based on HTTP/1.1.
  • proxy_set_header Upgrade $http_upgrade;​​: Set the Upgrade header to tell the backend that this is a WebSocket upgrade request.
  • proxy_set_header Connection "upgrade";​​: Set the Connection header to tell the backend connection that needs to be upgraded.
  • proxy_set_header Host $host;​​: Set the Host header to pass the host name requested by the client.
  • proxy_read_timeout 86400s;​​ and proxy_send_timeout 86400s;​​: Set the read and send timeout time to 24 hours to prevent the connection from being closed due to long-term no data transmission.

5. Test configuration

After saving the configuration file, test whether the Nginx configuration is correct:

sudo nginx -t

If there is no error, reload Nginx to apply the new configuration:

sudo systemctl reload nginx

6. Verify WebSocket connection

You can use a browser or other tool (such as wscat) to verify that the WebSocket connection is working properly. For example, use wscat:

npm install -g wscat
wscat -c ws://your_domain.com/ws/

If the connection is successful, it means that Nginx has correctly configured WebSocket support.

This is the end of this article about the detailed tutorial on Nginx configuring WebSocket. For more related content on Nginx configuring WebSocket, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!