Nginx反向代理异常:带端口可访问API,不带则报502错误
问题排查与解决方案
问题概述
在AWS EC2实例上通过PM2运行NestJS应用(监听3001端口),已用Certbot/Let's Encrypt配置Nginx SSL,将staging.api.example.com反向代理到本地http://127.0.0.1:3001,出现以下异常:
- 访问
staging.api.example.com返回502 Bad Gateway - 访问
staging.api.example.com:3001返回404错误 - 访问有效API路由
staging.api.example.com:3001/users一切正常
核心原因分析
- 协议不匹配:NestJS应用配置了HTTPS,但Nginx反向代理用HTTP协议访问本地3001端口,导致连接被后端提前关闭(对应Nginx错误日志中的
upstream prematurely closed connection)。 - 根路由缺失:
staging.api.example.com:3001返回404,是因为NestJS未配置根路径/的路由处理逻辑。 - 端口访问逻辑:直接加3001端口能访问,是因为安全组开放了该端口;不加端口时请求走Nginx的443端口,但Nginx与后端的连接因协议冲突失败。
具体修复步骤
1. 移除NestJS的HTTPS配置
Nginx已完成SSL终止,后端无需再启用HTTPS,修改代码如下:
const app = await NestFactory.create(AppModule, { cors: true, // 删除httpsOptions相关配置 }); await app.listen(3001);
修改后重启PM2服务:
pm2 restart example
2. 调整Nginx的Host头配置
当前proxy_set_header Host $host:$server_port;会将Host设置为staging.api.example.com:443,可能导致后端路由匹配异常,改为:
proxy_set_header Host $host;
重启Nginx生效:
sudo systemctl restart nginx
3. 可选:添加NestJS根路由处理
若需要根路径/返回正常响应,在任意控制器中添加:
@Get('/') getRootStatus() { return { status: 'running', message: 'API service is online' }; }
4. 安全组规则优化(可选)
由于所有请求均通过Nginx的80/443端口转发,可关闭安全组中3001端口的对外访问权限,仅保留本地回环访问,减少不必要的暴露面。
验证修复
- 访问
staging.api.example.com应返回正常响应(若配置了根路由)或对应API结果 - 访问
staging.api.example.com/users保持正常 - 若关闭了3001端口的安全组规则,
staging.api.example.com:3001将无法访问
内容的提问来源于stack exchange,提问作者thedealedge
相关产品推荐
相关产品推荐

