Current Location: Home> Latest Articles> Complete Guide to Enabling WebSocket Support with Nginx Reverse Proxy

Complete Guide to Enabling WebSocket Support with Nginx Reverse Proxy

M66 2025-07-09

Understanding WebSocket Protocol and the Role of Nginx

WebSocket is a full-duplex communication protocol based on TCP, allowing real-time, persistent two-way communication between a server and a client. It's ideal for use cases like instant messaging, live updates, and real-time data streaming. In real-world deployments, Nginx often serves as a reverse proxy to manage and relay WebSocket connections.

Ensure Nginx is Installed

Before proceeding, make sure Nginx is properly installed on your server. If not, install it using the appropriate command for your operating system.

Modify Nginx Configuration to Support WebSocket

To enable WebSocket support in Nginx, you'll need to adjust the configuration file. Add the following code to the http block:

map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

upstream backend {
    server 127.0.0.1:8080;
}

This section maps the Upgrade header to a custom variable $connection_upgrade and defines an upstream server named backend pointing to a local backend service.

Configure the server Block for WebSocket Proxying

Inside the server block, add the following location directive to handle WebSocket requests:

location /websocket {
    proxy_pass http://backend;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection $connection_upgrade;
}

This setup defines the proxy path and forwards the WebSocket requests while preserving required headers to maintain the protocol connection.

Restart Nginx to Apply Changes

After saving the updated configuration, restart the Nginx service to apply the changes:

sudo service nginx restart

Test the WebSocket Connection

You can use a WebSocket client tool or create a basic HTML page to test the WebSocket connection. Here's a simple example:

var ws = new WebSocket("ws://your_domain/websocket");

ws.onopen = function() {
    console.log("Connected to WebSocket");
};

ws.onmessage = function(event) {
    console.log("Received message: " + event.data);
};

ws.onclose = function() {
    console.log("Disconnected from WebSocket");
};

Save the above code as an HTML file and open it in a browser. If you see the “Connected to WebSocket” message in the browser console, the connection is successfully established.

Conclusion

By configuring Nginx as a reverse proxy, you can enable WebSocket protocol support for your applications. This not only enhances communication efficiency but also benefits from Nginx’s performance and flexibility. However, keep in mind that Nginx itself does not handle the WebSocket logic—it merely forwards the connection to the backend server. For more advanced WebSocket implementations, consider using dedicated WebSocket server solutions.