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

基于NiceGUI+Nginx的VPS部署中WebSocket升级失败问题排查

解决NiceGUI+Nginx部署下WebSocket连接失败的问题

问题场景

在VPS上通过NiceGUI结合Nginx搭建服务,子域名的HTTP请求可正常路由到后端并返回HTML内容,但WebSocket连接始终失败:

  • 服务端报错:ERROR:engineio.server:Invalid websocket upgrade (further occurrences of this error will be logged with level INFO)
  • 浏览器报错:manager.js:108 WebSocket connection to 'wss://{你的子域名}/_nicegui_ws/socket.io/?client_id=ce259c07-9781-4739-9faa-051f24e911bd&EIO=4&transport=websocket' failed
  • 本地使用on_air模式运行完全正常,排查确认核心问题:Nginx未传递HTTP_UPGRADE请求头,且VPS后端收到的scheme为https而非预期的ws

解决方案

修改Nginx的子域名配置,在location /块中添加WebSocket代理所需的头信息及长连接超时设置,确保后端能正确处理WebSocket升级请求。

修改后的Nginx配置

server {
    listen 80;
    server_name {你的子域名};
    # 强制跳转到HTTPS(推荐启用)
    return 301 https://$host$request_uri;
}
server{
    listen 443 ssl;
    server_name {你的子域名};
    ssl_certificate /etc/nginx/ssl/{你的子域名}_ssl_certificate.cer;
    ssl_certificate_key /etc/nginx/ssl/_.{你的子域名}_private_key.key;

    location / {
        proxy_pass http://127.0.0.1:8080;
        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_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        # 长连接超时设置,避免WebSocket连接被过早断开
        proxy_connect_timeout 7d;
        proxy_send_timeout 7d;
        proxy_read_timeout 7d;
    }
}

关键配置说明

  1. proxy_set_header Upgrade $http_upgrade:转发客户端的Upgrade请求头,告知后端需要将HTTP连接升级为WebSocket
  2. proxy_set_header Connection "upgrade":配合Upgrade头,明确请求的连接升级类型
  3. 长超时设置:WebSocket属于长连接,需延长Nginx代理超时时间,防止连接被主动断开
  4. HTTPS跳转:将HTTP请求强制跳转至HTTPS,确保WebSocket使用加密的wss协议

配置修改完成后,重启Nginx服务生效:

sudo systemctl restart nginx

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 22:42:27