Is there any way to pass client identity to Nginx (to get sticky session) when using WebSockets? Something similar to "X-Forwarded-For" header for HTTP ?
Websockets start their life under a HTTP upgrade handshake. Once the handshake is successfully completed you get back a long running bidirectional websocket connection.
If you use Nginx as a proxy for websockets then you can also use "X-Forwarded-For" but only on the handshake. See for example this simple configuration:
# WebSocket Proxy
#
# Simple forwarding of unencrypted HTTP and WebSocket to a different host
# (you can even use a different host instead of localhost:8080)
server {
listen 80;
# host name to respond to
server_name ws.example.com;
location / {
# switch off logging
access_log off;
# redirect all HTTP traffic to localhost:8080
proxy_pass http://localhost:8080;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# WebSocket support (nginx 1.4)
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
... and some references on this page.
You configure what Nginx should send along in the upgrade request (the info you use to identify the client) and it will be your backend server's job to use the information from the handshake to identify the client and then associate the websocket connection to your client. Based on that association, any message that comes on that websocket connection belongs to the previously identified client.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With