CodexBloom - Programming Q&A Platform

Nginx Reverse Proxy Not Handling WebSocket Connections Properly on Ubuntu 20.04

👀 Views: 442 đŸ’Ŧ Answers: 1 📅 Created: 2025-08-27
nginx websockets ubuntu node.js JavaScript

I've hit a wall trying to After trying multiple solutions online, I still can't figure this out. I'm trying to set up an Nginx reverse proxy for a Node.js application that uses WebSockets on an Ubuntu 20.04 server. Everything works fine for regular HTTP requests, but WebSocket connections unexpected result with the following behavior in the browser console: `WebSocket connection to 'ws://mydomain.com/socket' failed: behavior during WebSocket handshake: Unexpected response code: 400`. I've ensured that the WebSocket connection is properly initiated with `ws://` even when served over HTTPS. In my Nginx configuration, I have the following setup: ```nginx server { listen 80; server_name mydomain.com; location / { 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; 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; } } ``` I've tried adding `proxy_set_header Upgrade $http_upgrade;` and `proxy_set_header Connection "upgrade";`, but the scenario continues. Additionally, I checked my Node.js application, and it listens correctly for WebSocket connections. I've also ensured that there are no firewall rules blocking the WebSocket traffic. What could be causing this 400 behavior, and how can I resolve the scenario to allow WebSocket connections through Nginx? Am I missing something obvious? My development environment is Windows 10. Thanks in advance! I recently upgraded to Javascript LTS. Has anyone else encountered this? This is part of a larger desktop app I'm building.