不走 nginx 的代理,请求连接 websocket,总需要带上端口号。比如
new WebSocket("wss://www.xxx.com:9958")
,通过 nginx 的代理就可以实现这样的请求,比如new WebSocket("wss://www.xxx.com/wss")
一波操作
vim www.xxx.com.conf
upstream websocket {
# wss 配置代理到 127.0.0.1:9958
server 127.0.0.1:9958;
}
server
{
listen 80;
server_name xxx.com www.xxx.com;
return 301 https://www.xxx.com$request_uri;
}
server
{
listen 443 ssl http2;
server_name xxx.com www.xxx.com;
if ($host = 'xxx.com' ){
return 301 https://www.xxx.com$request_uri;
}
ssl_certificate /service/nginx/conf/ssl/www.xxx.com.pem;
ssl_certificate_key /service/nginx/conf/ssl/www.xxx.com.key;
location /wss {
# 代理到上边的自定义的地址
proxy_pass http://websocket;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
}
…
重启, nginx。
其实,在 proxy_pass 这里,可以直接设置为 127.0.0.1:9958
还有请求的时候,域名后一定要带上 wss 。