How to configure WebSocket connections in nginx?
To set up Nginx to support WebSocket connections, the following steps need to be taken:
- Open the configuration file of Nginx (usually located at /etc/nginx/nginx.conf).
- 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";
}
}
- 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”.
- 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.
- – Please provide me with the URL for your WebSocket server.
- Save and close the configuration file.
- Check the syntax of nginx configuration.
- 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.