您的位置:首页 > 房产 > 家装 > nginx代理webSocket请求

nginx代理webSocket请求

2024/10/6 16:21:42 来源:https://blog.csdn.net/weixin_42675423/article/details/139232705  浏览:    关键词:nginx代理webSocket请求

1、webSocket IP访问

一个web版的SSH工具,通过IP访问是正常的,如下:

2、nginx代理访问失败

代理配置如下:

这是简单代理http请求的配置

#gowebssh
server {listen 80;server_name ssh.shuizhu.vip;location / {proxy_pass http://116.205.237.115:31736;}
}

在连接Linux终端时,连接失败,按F12打开浏览器控制台,发现报错:

报错中提示ws://,证明是websocket类型的请求代理是失败的!

WebSocket connection to 'ws://ssh.shuizhu.vip/api/ssh/conn?h=17&w=198&session_id=qe7hwqm7598bdbf&Authorization=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJJZCI6MSwiaXNzIjoiZ29fd2ViX3NzaCIsImV4cCI6MTcxNjc4MDMzOH0.PSvWqUD4lcFyEWaLWQLC9ILBoa98Zymwy06ka33Pa1w' failed: Error during WebSocket handshake: Unexpected response code: 400

3、nginx代理websocket访问

步骤2中的nginx,只是配置了http类型的代理请求,对于websocket类型并没有配置,正确配置如下:

#gowebssh
server {listen 80;#location /api/ssh/conn代理必须在前面,否则会被下方的location /取代#目的是为了请求中存在/api/ssh/conn优先转发到该块配置中location /api/ssh/conn {proxy_pass http://116.205.237.115:31736/api/ssh/conn; #这里是http不是ws,不用怀疑,代理的ip和port写ws访问的实际地址proxy_http_version 1.1; #这里必须使用http 1.1#下面两个必须设置,请求头设置为ws请求方式proxy_set_header Upgrade $http_upgrade;proxy_set_header Connection "upgrade";}server_name ssh.shuizhu.vip;location / {#proxy_pass http://116.205.237.115:31736;proxy_pass http://192.168.5.83:31736;}
}

注意:通过报错得知:我的websocket类型的url中,带有/api/ssh/conn(其他的websocket请求,按实际配置即可),因此在localion中配置即可,并代理至对应:http://IP:PORT/api/ssh/conn

4、重启nginx

nginx -s reload

5、测试

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com