Nginx Reverse Proxy Builder · WebSockets / Socket.IO

Nginx Reverse Proxy Config for Socket.IO & WebSockets (Upgrade & 3600s)

Generate an Nginx reverse proxy server block for WebSockets / Socket.IO with URL prefix rewrite previews, Certbot SSL redirects, WebSocket upgrade headers, and Docker DNS checks.

Written & verified by Chathura Prabashana · Updated November 2026

1. Adjust stack settings or load a test scenario2. Inspect live diagnostics3. Copy generated config
Quick-Test Scenarios:

1. Domain, Routing & Upstream

2. TLS, WebSockets & Directives

# /etc/nginx/sites-available/ws.example.com.conf
# Generated by OpsCheck DevTools — Validate with: sudo nginx -t && sudo systemctl reload nginx

# Required in http {} context (or top of sites-available file) for clean WebSocket upgrades
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

server {
    listen 80;
    listen [::]:80;
    server_name ws.example.com;

    # Redirect all plaintext HTTP traffic permanently to HTTPS
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name ws.example.com;

    # Let's Encrypt Certbot TLS Certificates
    ssl_certificate     /etc/letsencrypt/live/ws.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/ws.example.com/privkey.pem;
    ssl_protocols       TLSv1.2 TLSv1.3;
    ssl_ciphers         HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;

    client_max_body_size 10M;

    # Baseline HTTP Security Headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    location /socket.io/ {
        proxy_pass http://127.0.0.1:4000;
        proxy_http_version 1.1;
        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;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Port $server_port;

        # WebSocket & Upgrade support (requires map $http_upgrade $connection_upgrade)
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_cache_bypass $http_upgrade;

        proxy_connect_timeout 15s;
        proxy_send_timeout 3600s;
        proxy_read_timeout 3600s;
    }
}
$sudo nginx -t && sudo systemctl reload nginx
URL Routing TransformationPrefix Preserved
GET https://ws.example.com/socket.io/usershttp://127.0.0.1:4000/socket.io/users

Strip Prefix OFF: Nginx preserves the full URI so upstream receives '/socket.io/users'.

Configuration Diagnostics

  • infoPrefix Preserved (/socket.io/ Forwarded Intact)

    GET https://ws.example.com/socket.io/users -> Upstream receives http://127.0.0.1:4000/socket.io/users. Strip Prefix OFF: Nginx preserves the full URI so upstream receives '/socket.io/users'.

  • passWebSocket Upgrade & Extended Timeout (3600s) Enabled

    Configured HTTP/1.1 Upgrade, Connection $connection_upgrade map, and extended proxy_read_timeout for persistent real-time sockets.

  • infoSingle-Layer CORS Policy Reminder

    This configuration intentionally omits Access-Control-Allow-Origin headers so your upstream backend framework (Laravel, FastAPI, Express, ASP.NET Core) owns CORS cleanly without duplicate header rejections.

Runs locally in your browser. Domain names and upstream topology are never sent to a server.

Common Nginx Error Log Pattern (WebSockets / Socket.IO)

When upstream sockets, timeouts, body limits, or Docker DNS rules are misconfigured for WebSockets / Socket.IO, Nginx typically records an entry matching the log line below inside /var/log/nginx/error.log:

/var/log/nginx/error.log

2026/11/22 18:19:52 [info] 5041#5041: *2099 upstream timed out (110: Connection timed out) while reading upstream, client: 198.51.100.77, server: ws.example.com, request: "GET /socket.io/?EIO=4&transport=websocket HTTP/1.1", upstream: "http://127.0.0.1:4000/socket.io/?EIO=4&transport=websocket", host: "ws.example.com"

Reverse Proxy Architecture & Header Forwarding for WebSockets / Socket.IO

Proxying WebSockets and Socket.IO through Nginx requires explicit HTTP/1.1 hop-by-hop header forwarding because Upgrade and Connection headers are never proxied automatically by Nginx. By default, Nginx speaks HTTP/1.0 to upstream servers and strips the Upgrade header; causing every wss:// handshake to fail immediately with HTTP 400 Bad Request or fall back permanently to inefficient Socket.IO HTTP long-polling.

Even after adding proxy_http_version 1.1 and Upgrade $http_upgrade, two subtle production failures routinely plague real-time apps: 60-second idle disconnects and multi-worker Socket.IO handshake drops. Because Nginx closes any proxied connection that stays silent for proxy_read_timeout (60 seconds by default), quiet chat rooms or live dashboards disconnect and reconnect in an endless 60-second loop unless proxy_read_timeout is raised (e.g., 3600s) and heartbeats stay active.

Using the map $http_upgrade $connection_upgrade pattern, instead of hardcoding proxy_set_header Connection "upgrade", is a critical Nginx best practice. Socket.IO initially connects with standard HTTP polling before upgrading to WebSockets; the map directive sends Connection: upgrade ONLY when the client requests an upgrade and cleanly sets Connection: close on non-upgrade requests.

When scaling Socket.IO across multiple Node.js or Python backend containers behind an Nginx upstream {} block, sticky sessions (ip_hash or hash $remote_addr consistent) are mandatory unless clients connect purely via transports: ["websocket"]. Without sticky routing, Socket.IO's initial HTTP polling SID lands on worker A while the WebSocket upgrade lands on worker B, producing HTTP 400 "Session ID unknown."

Production WebSocket gateways running Socket.IO or raw ws behind Nginx require end-to-end observability across browser DevTools Network WS frames, Nginx connection metrics (stub_status), and OS socket limits (fs.file-max and net.core.somaxconn). When debugging intermittent reconnect storms, compare the timestamp of client disconnect events against Nginx's proxy_read_timeout and any upstream load balancer idle timeout; matching heartbeat intervals below the shortest timeout in the chain guarantees smooth, uninterrupted real-time messaging.

Step-by-Step Nginx & WebSockets / Socket.IO Deployment Guide

Apply the Nginx server block above alongside these upstream framework trust-proxy settings so HTTPS detection, real client IPs, and reload safety work reliably in production.

  1. 1Define the Connection Upgrade Map and Extended Timeout in Nginx

    /etc/nginx/sites-available/ws.example.com.conf

    Include map $http_upgrade $connection_upgrade outside the server block, set proxy_http_version 1.1 inside location /socket.io/, disable proxy_buffering for low-latency frames, and raise proxy_read_timeout to 3600s.

    /etc/nginx/sites-available/ws.example.com.confnginx
    map $http_upgrade $connection_upgrade {
        default upgrade;
        ''      close;
    }
    
    # For multi-node Socket.IO clusters, enable sticky routing:
    upstream socketio_nodes {
        ip_hash;
        server 127.0.0.1:4000;
        server 127.0.0.1:4001;
    }
  2. 2Configure Socket.IO Server Ping Intervals Below Nginx Timeout

    src/socketServer.ts

    Ensure Socket.IO's pingInterval (default 25s) and pingTimeout (default 20s) remain well below Nginx's proxy_read_timeout so active connections constantly refresh Nginx's idle timer.

    src/socketServer.tstypescript
    import { Server } from 'socket.io';
    import http from 'node:http';
    
    const httpServer = http.createServer();
    const io = new Server(httpServer, {
      path: '/socket.io/',
      pingInterval: 25000,
      pingTimeout: 20000,
      cors: {
        origin: ['https://app.example.com'],
        credentials: true,
      },
    });
    
    httpServer.listen(4000, '127.0.0.1');
  3. 3Tune Nginx Worker Connections for High-Concurrency Sockets

    /etc/nginx/nginx.conf

    Every persistent WebSocket occupies two file descriptors in Nginx (browser-to-Nginx plus Nginx-to-upstream). Raise worker_rlimit_nofile and worker_connections before running production load tests.

    /etc/nginx/nginx.confnginx
    worker_processes auto;
    worker_rlimit_nofile 65535;
    
    events {
        worker_connections 16384;
        multi_accept on;
    }
  4. 4Verify Live WSS Handshake Status 101 Switching Protocols

    terminal

    Reload Nginx and test the WebSocket upgrade handshake with curl to confirm HTTP 101 Switching Protocols is returned instead of 400 or 502.

    terminalbash
    sudo nginx -t && sudo systemctl reload nginx
    
    curl -i -N \
      -H "Connection: Upgrade" \
      -H "Upgrade: websocket" \
      -H "Sec-WebSocket-Version: 13" \
      -H "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==" \
      "https://ws.example.com/socket.io/?EIO=4&transport=websocket"

Common WebSockets / Socket.IO Nginx Reverse Proxy Pitfalls

Review these three production failure modes before reloading Nginx on staging or live servers.

Pitfall 1

Forgetting proxy_http_version 1.1; (Nginx Defaults to HTTP/1.0)

WebSocket Upgrade handshakes strictly require HTTP/1.1. Even if you set Upgrade and Connection headers, omitting proxy_http_version 1.1 causes Nginx to downgrade the upstream request to HTTP/1.0 and fail every wss:// connection.

Pitfall 2

Socket.IO "Session ID unknown" (HTTP 400) Across Multiple Upstreams

With round-robin load balancing across two Node processes, Socket.IO's initial polling handshake hits server 1 while the upgrade request hits server 2. Use ip_hash in Nginx upstream {} (and the Redis adapter in Socket.IO) or force transports: ["websocket"] on clients.

Pitfall 3

Cloudflare or Load Balancer Idle Timeout Shorter Than Nginx 3600s

If Cloudflare Proxy (100-second idle timeout) or AWS ALB sits in front of Nginx, idle WebSockets still drop even with Nginx at 3600s unless your server emits application-level ping frames every 25–45 seconds.

Related Tools

Pair this Nginx reverse proxy block with healthcheck-gated Docker Compose orchestration and verified browser CORS headers:

Frequently Asked Questions

Why does my WebSocket disconnect after exactly 60 seconds behind Nginx?
Nginx's default proxy_read_timeout is 60s. If neither the upstream server nor client transmits a frame within 60 seconds, Nginx assumes the upstream hung and closes the socket. Raise proxy_read_timeout to 3600s and send periodic WebSocket ping frames.
Why is map $http_upgrade $connection_upgrade better than Connection "upgrade"?
Hardcoding proxy_set_header Connection "upgrade" sends an invalid Upgrade connection header on ordinary HTTP GET/POST calls (such as Socket.IO polling requests). Using map only sends "upgrade" when $http_upgrade is non-empty and cleanly sends "close" otherwise.
Should I disable Gzip on WebSocket-only Nginx locations?
Yes. WebSocket binary/text frames use permessage-deflate negotiation at the WebSocket protocol layer rather than HTTP Content-Encoding gzip. Keeping gzip off on dedicated WebSocket endpoints avoids unnecessary overhead.
Does HTTP/2 in Nginx listen 443 ssl http2 break WebSockets?
No. Browsers automatically negotiate HTTP/1.1 (or RFC 8441 extended CONNECT where supported) for wss:// handshakes while regular HTTPS requests benefit from HTTP/2 on the same server block.
Browse all 10 Nginx guides →