我在 nginx 配置(nginx 1.6.0、ubuntu 14.04)中有三个用于 http 的服务器块(虚拟主机)和一个用于 websocket 的服务器块。
server {
listen 80;
listen [::]:80;
server_name h3400.domain.com;
location / {
proxy_pass http://localhost:3400/;
proxy_http_version 1.1;
proxy_set_header Host $host;
}
}
# this one for websocket on ws://h3400.domain.com:3000/
server {
listen 3000;
listen [::]:3000;
server_name h3400.domain.com;
location / {
proxy_pass http://localhost:3001;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
server {
listen 80;
listen [::]:80;
server_name h3500.domain.com;
location / {
proxy_pass http://localhost:3500/;
proxy_http_version 1.1;
proxy_set_header Host $host;
}
}
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name domain.com;
///other default nginx server block settings///
}
现在,在浏览器开发者控制台(最新的 ff 和 chrome)中我写道:
var ws = new WebSocket('ws://domain.com:3000', 'Site');<br>
ws.readyState;
结果我得到:
> 1
我测试的连接字符串:
ws://domain.com:3000
ws://h3400.domain.com:3000
ws://h3500.domain.com:3000
并且所有的连接字符串都给出一个结果:1.表示成功连接到websocket后端。
它仍然会与 3001 端口建立连接(我在 websocket 后端的日志中看到它),并且不检查 server_name 或端口,但它已配置为server_name h3400.domain.com;
并在每个服务器块的启动时配置。