有没有办法在使用WebSockets时将客户端身份传递给Nginx(以获得粘性会话)?类似于HTTP中的“X-Forwarded-For”头文件?
Websockets 通过 HTTP 升级握手开始其生命周期。一旦握手成功完成,您将收到一个长期运行的双向 websocket 连接。
如果您使用 Nginx 作为 websocket 的代理,则只能在握手时使用 "X-Forwarded-For"。例如,请参见 这个简单配置:
# 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";
}
}
您可以在此页面上找到一些相关参考资料。
您可以配置Nginx应该在升级请求中发送什么信息(用于识别客户端的信息),然后由后端服务器使用握手信息来识别客户端,并将websocket连接与客户端关联起来。基于这种关联,任何在该websocket连接上收到的消息都属于先前识别的客户端。