You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

用于Phoenix+WebSockets的Nginx配置是否正确?WebSocket连接失败求助

解决WebSocket连接失败的Nginx配置问题

问题分析

你遇到的socket.js:229 WebSocket connection to 'ws://sitename.io/socket/websocket?token=&vsn=2.0.0' failed报错,核心原因是Nginx的location路径匹配规则和请求路径不匹配:

  • 请求路径是/socket/websocket(不带末尾斜杠)
  • 但Nginx配置的location是/socket/websocket/(带末尾斜杠),导致请求不会命中WebSocket专属代理配置,而是走了根路径的普通proxy_pass,无法建立WebSocket连接。

修复方案

方案1:调整location路径(最直接)

把带末尾斜杠的location /socket/websocket/改成不带斜杠的location /socket/websocket,同时新增Host头确保后端识别请求域名:

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name sitename.io;

    location /socket/websocket {
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_set_header Host $host;
            proxy_pass http://localhost:4000/socket/websocket;
        }

    location / {
            proxy_pass http://localhost:4000/;
    }
}

方案2:正则匹配(兼容带/不带斜杠的请求)

如果需要同时兼容/socket/websocket和/socket/websocket/的请求,可使用正则location:

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name sitename.io;

    location ~ ^/socket/websocket(/?)$ {
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_set_header Host $host;
            proxy_pass http://localhost:4000/socket/websocket;
        }

    location / {
            proxy_pass http://localhost:4000/;
    }
}

额外注意事项

  • 确认后端服务(localhost:4000)确实监听/socket/websocket路径的WebSocket连接
  • 重启Nginx使配置生效:sudo nginx -s reload
  • 若仍失败,查看Nginx错误日志(通常在/var/log/nginx/error.log)获取具体报错信息

内容的提问来源于stack exchange,提问作者bezzoon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 06:15:05