Web / NGINX Interview questions
How does NGINX handle WebSocket proxying?
WebSockets start as a normal HTTP request that "upgrades" to a persistent, bidirectional TCP connection - and by default, NGINX's proxying doesn't forward the headers that make that upgrade work, so WebSocket connections need explicit configuration.
location /ws/ { proxy_pass http://backend_app; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; }
proxy_http_version 1.1 is required because WebSocket upgrades depend on HTTP/1.1 semantics. The two proxy_set_header lines forward the client's Upgrade request through to the backend and explicitly set Connection: upgrade, since NGINX would otherwise send its own default Connection header value and break the handshake.
Once established, NGINX keeps the connection open and relays data in both directions for as long as the WebSocket session lasts, rather than treating it as a normal request/response cycle - which also means long proxy_read_timeout values are often needed, since an idle-but-open WebSocket shouldn't be killed by a short default timeout meant for regular HTTP requests.
More Related questions...