前端连接websocket服务报错 Unexpected response code: 301

前端连接websocket服务报错 Unexpected response code: 301

websocket后端服务正常,监听正常,可以通过简单的前端代码进行连接,但是通过nginx反向代理后报错Error during WebSocket handshake: Unexpected response code: 301

直连测试

假设我的webosocket服务tcp监听端口为8082,服务端ip为192.168.10.3,通过这个简单的js程序,用浏览器打开,查看控制台,网络中的ws,可以看到是能正常连接的,返回状态码为101.

js 复制代码
<script>
// 创建一个 WebSocket 实例
const socket = new WebSocket('ws://192.168.10.3:8082/ws');
 
// 当 WebSocket 打开时,输出信息
socket.addEventListener('open', function (event) {
    console.log('WebSocket 连接已打开');
});
 
// 当接收到消息时,输出数据
socket.addEventListener('message', function (event) {
    console.log('收到消息:', event.data);
});
 
// 当 WebSocket 关闭时,输出信息
socket.addEventListener('close', function (event) {
    console.log('WebSocket 连接已关闭');
});
 
// 当遇到错误时,输出错误信息
socket.addEventListener('error', function (event) {
    console.error('WebSocket 出现错误');
});

</script>

301重定向

301 是永久重定向状态码,通常发生在:

  • WebSocket 连接请求的 URL 缺少尾部斜杠

  • Nginx 配置中有重写规则导致 WebSocket 请求被重定向

  • WebSocket 连接尝试使用 HTTP 但服务器期望 HTTPS(或反之)

修改nginx配置

原关于websocket代理配置片段如下

shell 复制代码
location /ws/ {
  proxy_pass http://192.168.10.3:8082/ws;
  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;
}

修改如下:

shell 复制代码
location /ws {
    proxy_pass http://192.168.10.3:8082/ws;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    
    # 以下为 WebSocket 特定配置
    proxy_read_timeout 60s;
    proxy_redirect off;
}

重新加载nginx配置

shell 复制代码
nginx -s reload

前端页面重新加载后ws连接恢复正常。

相关推荐
可可嘻嘻大老虎1 天前
nginx无法访问后端服务问题
运维·nginx
皇帝要考研1 天前
【ISO 13400-2:2019】核心配置项
网络·网络协议
JoySSLLian1 天前
IP SSL证书:一键解锁IP通信安全,高效抵御网络威胁!
网络·人工智能·网络协议·tcp/ip·ssl
bantinghy1 天前
Nginx基础加权轮询负载均衡算法
服务器·算法·nginx·负载均衡
Dontla1 天前
Vite代理 vs Nginx代理(开发环境用Vite,生产环境用Nginx)
运维·nginx
云小逸1 天前
【网络通信】DNS、SNMP、DHCP 等 UDP 服务解析
网络·网络协议·udp
No Silver Bullet1 天前
Nginx 内存不足对Web 应用的影响分析
运维·前端·nginx
Access开发易登软件1 天前
Access 窗体中实现数字滚动动画:Timer + Easing 的技术实现
运维·数据库·nginx·microsoft·access
半壶清水2 天前
[软考网规考点笔记]-操作系统核心知识及历年真题解析
网络·网络协议·算法
凌寒112 天前
minio预签名访问地址经过Nginx代理后返回403问题
服务器·网络·nginx