Networking
WebSocket vs HTTP: How They Differ and How to Proxy WebSockets in Nginx
By NileVPS Team · Published · 4 min read
اقرأ المقال بالعربيChat apps, live dashboards, multiplayer games and collaborative editors all need the server to push data to the browser the moment something happens. Classic HTTP was not designed for that: the client asks, the server answers, and the exchange is over. WebSocket fills the gap by turning a single HTTP request into a long-lived, two-way channel. This guide explains how the two protocols differ, when each one is the right tool, and how to put a WebSocket application behind Nginx on a VPS without connections dropping every minute.
How HTTP works
HTTP is a request-response protocol. The browser opens a TCP connection (usually encrypted with TLS), sends a request such as GET /api/orders, and the server replies with headers and a body. With HTTP/1.1 keep-alive and HTTP/2 multiplexing, the TCP connection can be reused, but the rule stays the same: the server only speaks when spoken to.
To simulate real-time updates over plain HTTP, developers use:
- Short polling: ask every few seconds whether anything changed. Simple, but wasteful.
- Long polling: the server holds the request open until there is news, then the client immediately asks again.
- Server-Sent Events (SSE): a single long response that streams text events from server to client. One direction only.
How WebSocket works
A WebSocket connection starts as an ordinary HTTP/1.1 request carrying special headers:
GET /ws HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13If the server agrees, it answers 101 Switching Protocols with a matching Sec-WebSocket-Accept header. From that moment the TCP connection no longer carries HTTP. Both sides exchange small binary or text frames whenever they want, in either direction, until one side closes it. The ws:// scheme is unencrypted; wss:// runs over TLS on port 443 and is what you should use in production.
Choosing between them
| Need | Better fit |
|---|---|
| Normal page loads, REST or JSON APIs | HTTP |
| Cacheable content behind a CDN | HTTP |
| Server pushes occasional updates, one direction | SSE over HTTP |
| Frequent messages in both directions (chat, games, editors) | WebSocket |
| Very low per-message overhead after connecting | WebSocket |
WebSocket is not a replacement for HTTP. Most real applications use both: HTTP for pages, authentication and file uploads, and a WebSocket for the live channel. Keep in mind that every open WebSocket is a persistent connection that occupies a file descriptor and some memory on your server, so capacity planning is about concurrent connections, not just requests per second.
Proxying WebSockets in Nginx
Nginx does not forward the Upgrade and Connection headers to the backend by default, because they are hop-by-hop headers. You have to pass them explicitly and use HTTP/1.1 toward the upstream. Put this map in the http block (for example in /etc/nginx/conf.d/websocket-map.conf):
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}Then, inside your server block:
location /ws/ {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
}The map sends Connection: upgrade only when the client actually asked for an upgrade, so the same location can still serve normal requests.
Why connections drop after 60 seconds
The most common complaint is that sockets close after exactly one minute of silence. That is Nginx's default proxy_read_timeout of 60 seconds: if the backend sends nothing for that long, Nginx closes the connection. Either raise the timeout as shown above, or, better, have the application send a ping frame every 20 to 30 seconds. Pings also keep NAT devices and load balancers from forgetting the connection; see our article on TCP keepalive tuning for the lower-level side of the same problem.
Test and reload:
sudo nginx -t && sudo systemctl reload nginxTesting the connection
From your own machine, check that the handshake returns 101:
curl -i -N --http1.1 \
-H "Connection: Upgrade" -H "Upgrade: websocket" \
-H "Sec-WebSocket-Version: 13" \
-H "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==" \
https://example.com/ws/For an interactive test, the websocat tool lets you type messages: websocat wss://example.com/ws/. In the browser, the Network tab filtered to "WS" shows each frame.
Capacity checklist
- Raise
worker_connectionsinnginx.conf(each proxied WebSocket uses two connections: client side and upstream side). - Raise the open-file limit for Nginx and your app, for example
LimitNOFILE=65535in the systemd unit. - Make sure port 443 is open in your cloud firewall; you never need to expose the backend port (3000 above) publicly.
- If you run several backend instances, use sticky sessions or a shared message broker such as Redis pub/sub, since a WebSocket stays attached to the instance that accepted it.
- Log disconnect reasons in the app so you can tell timeouts from crashes.
A small Linux VPS handles a surprising number of idle WebSocket connections, because idle sockets cost memory, not CPU. If you want to try a real-time app yourself, you can deploy a server and have Nginx in front of it in a few minutes.
FAQ
Does WebSocket work through Cloudflare or other proxies?
Most modern reverse proxies and CDNs support WebSocket, but each may have its own idle timeout. Send application-level pings regularly so the connection is never idle long enough to be cut.
Can Nginx proxy WebSockets over HTTP/2?
Browsers can open WebSockets over HTTP/2 when both sides support it, but the common and reliable setup is to proxy to your backend with proxy_http_version 1.1 and the Upgrade headers shown above. That works for clients connecting with either protocol version.
Should I use SSE instead of WebSocket?
If the server only needs to push updates and the client rarely sends anything, SSE is simpler: it is plain HTTP, reconnects automatically and passes through most proxies unchanged. Choose WebSocket when messages flow often in both directions.