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

Django Rest Framework中无法建立安全WebSocket(wss://)连接求助

解决wss://安全WebSocket连接失败的方法

你的ASGI和Channel配置本身没有问题,wss连接失败核心原因是SSL证书配置缺失或反向代理转发规则未正确设置,下面分两种常见场景给出解决方案:

场景1:直接用ASGI服务器(Daphne/Uvicorn)提供wss服务

开发或测试环境可以让ASGI服务器直接处理SSL:

  • 若使用Daphne,启动时添加SSL证书参数:
daphne -b 0.0.0.0 -p 443 --ssl-certfile /path/to/your/cert.pem --ssl-keyfile /path/to/your/private.key your_project.asgi:application
  • 若使用Uvicorn,启动命令为:
uvicorn your_project.asgi:application --host 0.0.0.0 --port 443 --ssl-certfile /path/to/your/cert.pem --ssl-keyfile /path/to/your/private.key

注意:证书路径要确保正确,生产环境建议使用正规CA签发的证书;开发环境用自签证书时,前端(如浏览器)需手动信任该证书才能正常连接。

场景2:生产环境用Nginx反向代理处理SSL(推荐)

生产环境通常用Nginx做反向代理,由Nginx处理SSL后,将wss请求转发到后端ASGI服务器:

  1. 确保Nginx已配置HTTPS(SSL证书部署完成),在server块中添加wss转发规则:
server {
    listen 443 ssl;
    server_name your-domain.com;

    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/private.key;

    # 转发HTTP请求到ASGI服务器的HTTP端口(示例为8000)
    location / {
        proxy_pass http://127.0.0.1:8000;
        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;
    }

    # 转发wss请求到ASGI服务器(端口与HTTP一致即可,ASGI会自动识别协议)
    location /ws/ {
        proxy_pass http://127.0.0.1:8000;
        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;
    }
}
  1. 重启Nginx服务,同时确保ASGI服务器(如Daphne/Uvicorn)正常监听对应端口(示例为8000)。

额外检查项

  • 前端连接地址需准确:例如wss://your-domain.com/ws/notifications/,避免路径或域名拼写错误
  • 防火墙/安全组需开放443端口(wss默认使用443端口)
  • 若使用自签证书,前端需信任该证书,否则会因证书验证失败拒绝连接

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 01:12:14