This guide walks you through setting up a WebSocket connection on a VPS where Nginx acts as a reverse proxy. You’ll learn how to configure Nginx to properly forward the Upgrade and Connection headers, so your real-time apps (chat, dashboards, games) work seamlessly behind the proxy. No prior Nginx expertise is needed, but basic command-line comfort is assumed.
What You’ll Need
- A VPS running Linux (Ubuntu/Debian or CentOS/RHEL) with Nginx installed.
- Your WebSocket application already running on a local port (e.g., 8080, 3000) on the same server.
- SSH access to the server with sudo privileges.
- A domain name pointing to your server’s IP (optional but recommended for production).
Step-by-Step
- Check your WebSocket app is listening locally. Run
curl -i http://localhost:8080(replace with your app’s port). If you get a response (even an error), the app is up. If not, start it and ensure it’s bound to 0.0.0.0 or localhost. - Back up your Nginx config. Copy the default config:
sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/default.bak(adjust path for your OS). - Edit the Nginx server block. Open the config file:
sudo nano /etc/nginx/sites-available/default(or your custom site). - Add a location block for WebSocket. Inside the
server { }block, add:location /ws/ { proxy_pass http://localhost:8080; 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-Forwarded-Proto $scheme; }Replace
/ws/with your app’s WebSocket path (e.g.,/socketor/). Theproxy_passmust point to the port your app listens on. - Set proxy timeouts (optional but recommended). WebSocket connections are long-lived. Add these lines inside the same location block to avoid premature disconnects:
proxy_read_timeout 3600s; proxy_send_timeout 3600s; proxy_connect_timeout 75s;
Adjust as needed.
- Test the config. Run
sudo nginx -t. If it reports errors, fix them (common issues: missing semicolons, wrong braces). - Reload Nginx.
sudo systemctl reload nginx(orsudo service nginx reload). - Test the WebSocket connection. Use a browser console or a tool like
wscat. For example, if your app is atws://yourdomain.com/ws, runwscat -c ws://yourdomain.com/ws. If you see a connection established, it works.
Common Mistakes
- Forgetting the Upgrade headers. Without
proxy_set_header Upgrade $http_upgradeandConnection "upgrade", Nginx treats the request as a normal HTTP request, and the WebSocket handshake fails. - Using HTTP/1.0. WebSockets require HTTP/1.1. Always set
proxy_http_version 1.1. - Wrong path in location. If your app listens on the root path, use
location / { }. If you use/ws/but your app expects the path to be stripped, you may need a rewrite or a different proxy_pass (e.g.,proxy_pass http://localhost:8080/;). - Not opening the firewall. Ensure your VPS firewall allows traffic on ports 80/443 (and 8080 if you’re testing directly).
- Timeout too low. Default proxy_read_timeout is 60s. If your WebSocket goes idle, Nginx will close it. Set higher timeouts.
Tips
- Use SSL/TLS. For production, set up HTTPS (e.g., with Certbot). Then use
wss://instead ofws://in your client. - Use a separate location for WebSocket vs. regular HTTP. If your app serves both, keep the WebSocket location specific (e.g.,
/ws/) and let other requests go to a normal proxy. - Monitor logs. Check
/var/log/nginx/error.logfor handshake failures. - Consider using Nginx’s built-in WebSocket support. Nginx has had native WebSocket proxying since version 1.3.13, so you don’t need any extra modules.
Troubleshooting
- Handshake fails with 400 Bad Request. Usually means the Upgrade headers are missing. Double-check your location block.
- Connection closes immediately. Check proxy_read_timeout. Also, ensure your app doesn’t have its own idle timeout.
- 404 Not Found. Your location path doesn’t match the client’s connection URL. Adjust either the location or the client’s path.
- 502 Bad Gateway. Nginx cannot reach your app. Verify the app is running and the proxy_pass port is correct.
- Mixed content errors. If your site is HTTPS, the WebSocket must be wss://. Use a relative URL in your client code (e.g.,
ws://" + location.host + "/ws"but with wss when https).
Frequently Asked Questions
Do I need to modify my WebSocket app code?
No. The Nginx configuration handles the proxying transparently. Your app sees a direct connection from Nginx.
Can I use Nginx with multiple WebSocket backends?
Yes, you can use upstream blocks and load balance, but WebSocket connections are sticky by nature (same server for the session). Use ip_hash or sticky sessions.
What if my app uses a different path for WebSocket?
Just change the location path accordingly. For example, if your app uses /socket, use location /socket { }.
Does Nginx support WebSocket compression?
Nginx passes through the permessage-deflate extension if both client and server support it. No extra config needed.
How do I test WebSocket from the command line?
Install wscat (npm install -g wscat) or use curl with the –include flag to see the handshake headers.
Is it safe to use the same server block for HTTP and WebSocket?
Yes, as long as you use separate location blocks. Nginx will route based on the URL path.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.
More cards in this drawer
- Skip Ryobi and Milwaukee? Harbor Freight Tools to Buy
- Funny Subreddits That Make You Laugh
- Why Retro Gaming Is Still Worth Playing Today
- Neptune Facts That Will Blow Your Mind
- Survival Crafting Game Fatigue: Why & How to Fix It
- Sell Your EV Now Before Prices Plummet?