Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nginx: What is the X-Forwarded-For alternative for WebSockets?

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 ?

like image 577
Alex Uslontsev Avatar asked Dec 08 '14 23:12

Alex Uslontsev


1 Answers

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.

like image 79
Bogdan Avatar answered Sep 21 '22 23:09

Bogdan