If your application needs to provide real-time updates, like live notifications or chat features, it might use WebSockets. To make sure your Nginx server can handle these WebSocket connections, you need to configure it properly. This guide will show you how to do that step by step.
I have an application running on https://example.com, and it uses WebSockets for live updates. The WebSocket connections look like this: wss://example.com/live-updates. To ensure that these connections work smoothly, you’ll need to adjust your Nginx configuration.
Step 1: Enable WebSocket Support in Nginx
Nginx supports WebSockets natively, so you don’t need to install extra modules. However, you need to make sure that your configuration allows WebSocket traffic to pass through to your backend server.
Step 2: Configure Your Nginx Server Block
Open your Nginx configuration file, typically found at /etc/nginx/sites-available/default or /etc/nginx/nginx.conf. Add the following configuration to your server block:
server {
listen 80;
server_name example.com;
# Other configurations (like root, index, etc.)
location /live-updates {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection “upgrade”;
proxy_set_header Host $host;
}
location / {
proxy_pass http://localhost:3000;
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-Forwarded-Proto $scheme;
}
}
What Does This Configuration Do?
proxy_pass: Forwards the WebSocket requests to the backend server running on localhost:3000.
proxy_http_version 1.1: Ensures that the HTTP version used is 1.1, which is necessary for WebSockets.
proxy_set_header Upgrade $http_upgrade and proxy_set_header Connection “upgradeâ€: These headers are required for upgrading the connection to a WebSocket.
Step 3: Restart Nginx
After making the changes, you need to restart Nginx to apply the new configuration. Run the following command:
sudo systemctl restart nginx
Conclusion
By following these simple steps, you can configure Nginx to handle WebSocket connections for your application. This ensures that your real-time features, like live updates or chat, work smoothly without any issues. Proper configuration will allow Nginx to efficiently manage both WebSocket and regular HTTP traffic.
The post How to Set Up Nginx to Handle WebSocket (wss://) Connections appeared first on TecAdmin.
Source: Read More