NGINX as a load balancer for WebSocket

 

To configure NGINX as a secure load balancer for WebSocket (wss://) connections, use an HTTP upgrade map, increase connection timeouts, and configure SSL termination. [1, 2]
Complete NGINX Configuration Example
Add this configuration inside your nginx.conf or site configuration file:
nginx
http {
    # Map dynamic connection upgrade headers
    map $http_upgrade $connection_upgrade {
        default upgrade;
        ''      close;
    }

    upstream websocket_backend {
        ip_hash; # Ensures sticky sessions for client connections
        server ://example.com;
        server ://example.com;
    }

    server {
        listen 443 ssl;
        server_name yourdomain.com;

        # SSL/TLS Certificates for WSS termination
        ssl_certificate /path/to/fullchain.pem;
        ssl_certificate_key /path/to/privkey.pem;

        location / {
            proxy_pass http://websocket_backend;
            
            # Required for WebSocket handshake
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection $connection_upgrade;
            
            # Standard proxy headers
            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;

            # Prevent idle timeouts from dropping long-lived connections (set to 24 hours)
            proxy_read_timeout 86400s;
            proxy_send_timeout 86400s;
            
            # Disable buffering for real-time data streaming
            proxy_buffering off;
        }
    }

    # Optional: Redirect HTTP to HTTPS
    server {
        listen 80;
        server_name yourdomain.com;
        return 301 https://$host$request_uri;
    }
}

NGINX as a load balancer for WebSocket

  To configure NGINX as a secure load balancer for WebSocket ( wss:// ) connections, use an HTTP upgrade map, increase connection timeouts, ...

Mais vistos