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

NestJS部署Ubuntu VPS后express-basic-auth致Swagger UI无法访问

问题描述

本地NestJS服务器中,用express-basic-auth保护Swagger UI的/docs*路径一切正常,但部署到Ubuntu VPS后,访问http://mydomain/docs时Chrome提示:

This site can’t be reachedThe web page at http://mydomain/docs might be temporarily down or it may have moved permanently to a new web address.
ERR_TOO_MANY_RETRIES

实现代码:

app.use(
  '/docs*',
  expressBasicAuth({
    challenge: true,
    users: {
      user: 'password',
    },
  }),
);
排查与解决方案

1. 检查VPS端口与防火墙配置

  • 确认VPS本地防火墙(如ufw)已开放服务监听端口(默认NestJS是3000,用反向代理则是80/443):
    执行命令:sudo ufw allow 3000(替换为实际端口),再执行sudo ufw reload。
  • 检查云服务商安全组规则,确保对应端口的入站流量权限已开启。

2. 修复反向代理(如Nginx)的请求头传递

若用Nginx做反向代理,未正确传递认证请求头会导致循环重试:

  • 修改Nginx配置,确保Authorization头被转发到后端:
    location /docs {
      proxy_pass http://localhost:3000/docs;
      proxy_set_header Authorization $http_authorization;
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
    }
    
  • 重启Nginx生效:sudo systemctl restart nginx

3. 调整express-basic-auth的challenge参数

当challenge: true时,服务器返回的WWW-Authenticate头可能被VPS上的代理层(CDN、负载均衡)拦截,引发重试循环:

  • 尝试将challenge设为false,手动处理认证:
    app.use(
      '/docs*',
      expressBasicAuth({
        challenge: false,
        users: {
          user: 'password',
        },
      }),
    );
    

4. 确认服务监听地址

确保NestJS服务监听0.0.0.0而非localhost,否则VPS外部无法访问:

  • 在main.ts中指定监听地址:
    await app.listen(3000, '0.0.0.0');
    

5. 检查服务运行状态

  • 确认NestJS服务在VPS上正常运行:pm2 status(用pm2管理时)或systemctl status your-service-name。
  • 查看服务日志排查认证错误:pm2 logs或journalctl -u your-service-name -f。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 23:29:58