Nginx 转发任意路径到WebSocket/WS,并过滤非WebSocket请求

前言

我需要WebSocket/ws能接受任意路径并转发,并过滤请求不包含WebSocket的不做操作

需要Nginx

WebSocket 接收任意路径请求

Nginxnginx.conf配置添加以下然后重启即可

1
2
3
4
5
6
7
8
9
10
11
location ^~ / {
proxy_redirect off;
# /ws修改为你的路径
rewrite ^(.*)$ /ws break;
# http://127.0.0.1:33684 修改为你的IP:PORT
proxy_pass http://127.0.0.1:33684;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $http_host;
}

过滤非WebSocket的请求

Nginxnginx.conf配置添加以下然后重启即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
location ^~ / {
proxy_redirect off;
if ($http_upgrade != "websocket") {
#root /data/wwwroot/default;
}
if ($http_upgrade = "websocket") {
# /ws修改为你的路径
rewrite ^(.*)$ /ws break;
# http://127.0.0.1:33684 修改为你的IP:PORT
proxy_pass http://127.0.0.1:33685;
}
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $http_host;
}

测试

测试网站

http://18.140.58.61/