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

2019-04-08 09:01发布

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 ?

1条回答
可以哭但决不认输i
2楼-- · 2019-04-08 09:22

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.

查看更多
登录 后发表回答