我使用nginx
作为我的WebSocket
流量的代理,效果很好。我的一个应用程序需要使用STOMP
,因为我选择了STOMP js库,它尝试通过Sec-WebSocket-Protocol
标头协商协议但我在添加此标头时遇到了麻烦nginx
回复。
nginx version: nginx/1.6.2
以下是我的服务器块:
server {
listen 80;
server_name mware.example.com;
client_max_body_size 100M;
keepalive_timeout 5;
root /srv/applications;
autoindex off;
location / {
# WebSocket
location = /ws {
proxy_read_timeout 10m;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_pass http://127.0.0.1:8000/;
proxy_redirect http://127.0.0.1:8000/ /;
# Custom headers
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE_PORT $remote_port;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
#add_header Sec-WebSocket-Protocol $http_sec_websocket_protocol;
add_header Sec-WebSocket-Protocol 'v10.stomp, v11.stomp';
}
}
}
因此尝试通过$http_sec_websocket_protocol
变量添加标题以及字面指定它,这些都不适用于我。以下是localhost
上的数据包捕获。
发送数据包:
T 10.3.2.100:36798 -> y.y.y.y:80 [AP]
GET /ws HTTP/1.1.
Host: mware.example.com.
Connection: Upgrade.
Pragma: no-cache.
Cache-Control: no-cache.
Upgrade: websocket.
Origin: file://.
Sec-WebSocket-Version: 13.
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.71 Safari/537.36.
Accept-Encoding: gzip, deflate, sdch.
Accept-Language: en-US,en;q=0.8.
Cookie: __utma=82131859.1920436741.1415282304.1421757291.1421760088.10; session_id_api=x.x.x.x-87eeca97-c6db-4010-bef8-f4875a6feb52; session_id_portal=x.x.x.x-ace62281-2446-4708-aa9d-4390eb41e02a.
Sec-WebSocket-Key: bGN7hB4fw7/JuF6A5vSf6A==.
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits.
Sec-WebSocket-Protocol: v10.stomp, v11.stomp.
Nginx回复:
T y.y.y.y:80 -> 10.3.2.100:36798 [AP]
HTTP/1.1 101 Switching Protocols.
Server: nginx/1.6.2.
Date: Tue, 17 Nov 2015 09:35:18 GMT.
Connection: upgrade.
Upgrade: websocket.
Sec-WebSocket-Accept: D34d7GBjjQkSC8jrjpixNmMxDMc=.
您可以看到Sec-WebSocket-Protocol
标题缺失。
在应用程序级别,我通过nginx接收格式正确的数据包,添加了自定义标题等等。
Upgrade: websocket
Connection: upgrade
Host: mware.example.com
X-Real-IP: x.x.x.x
REMOTE_PORT: 36798
X-Forwarded-For: x.x.x.x
Pragma: no-cache
Cache-Control: no-cache
Origin: file://
Sec-WebSocket-Version: 13
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.71 Safari/537.36
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Cookie: __utma=82131859.1920436741.1415282304.1421757291.1421760088.10; session_id_api=x.x.x.x-87eeca97-c6db-4010-bef8-f4875a6feb52; session_id_portal=x.x.x.x-ace62281-2446-4708-aa9d-4390eb41e02a
Sec-WebSocket-Key: bGN7hB4fw7/JuF6A5vSf6A==
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
Sec-WebSocket-Protocol: v10.stomp, v11.stomp
答案 0 :(得分:2)
如果响应代码等于200,201,204,206,301,302,303,304或307,则将指定字段添加到响应头。值可以包含变量。
您使用101代码回复。
从版本1.7.5开始,有always
标志,但您使用的是旧版本。您也可以考虑使用第三方模块,例如headers_more
或lua
。