【发布时间】:2015-02-06 18:21:50
【问题描述】:
在使用 WebSockets 时,有什么方法可以将客户端身份传递给 Nginx(以获得粘性会话)?类似于 HTTP 的“X-Forwarded-For”标头?
【问题讨论】:
在使用 WebSockets 时,有什么方法可以将客户端身份传递给 Nginx(以获得粘性会话)?类似于 HTTP 的“X-Forwarded-For”标头?
【问题讨论】:
Websocket 在 HTTP 升级握手下开始它们的生命。握手成功完成后,您将返回一个长时间运行的双向 websocket 连接。
如果您使用 Nginx 作为 websockets 的代理,那么您也可以使用“X-Forwarded-For”,但只能在握手时使用。例如见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";
}
}
...以及this page 上的一些参考资料。
您配置 Nginx 应在升级请求中发送的内容(用于识别客户端的信息),后端服务器的工作就是使用来自握手的信息来识别客户端,然后将 websocket 连接关联到你的客户。基于该关联,该 websocket 连接上的任何消息都属于先前识别的客户端。
【讨论】: