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

Nginx Server Block代理/api路径至Node服务出现404错误求助

Nginx反向代理404问题排查与解决

核心问题定位

你的情况是example.com/api/*请求无法转发到本地3001端口的Node服务,返回404,但本地curl localhost:3001正常,大概率是Nginx的反向代理规则配置错误,导致请求路径没有正确传递给后端服务。

检查并修正Nginx Server Block配置

打开你的Nginx站点配置文件(通常在/etc/nginx/sites-available/example.com或/etc/nginx/conf.d/example.com.conf),重点核对/api/相关的location规则:

正确的配置示例

server {
    listen 80;
    server_name example.com;

    # 处理Angular应用的example.com/app2访问
    location /app2 {
        root /var/www/angular-app/dist;  # 替换为你的Angular编译后静态文件路径
        try_files $uri $uri/ /app2/index.html;  # Angular单页应用路由 fallback
    }

    # 处理/api/路径转发到3001端口的Node服务
    location /api/ {
        proxy_pass http://localhost:3001/;  # 注意末尾的斜杠,这是关键!
        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;
    }
}

关键配置说明

  • proxy_pass末尾的斜杠:如果省略斜杠,Nginx会把/api/前缀一起传递给后端,比如请求example.com/api/login会被转发到http://localhost:3001/api/login,而如果你的Node服务路由是/login而非/api/login,就会触发404。加上斜杠后,Nginx会去掉/api/前缀,把/login传递给后端。
  • 若你的Node服务本身路由带/api前缀,需把proxy_pass改为http://localhost:3001;(去掉末尾斜杠)。

验证配置并重启Nginx

  1. 检查配置语法是否合法:
sudo nginx -t

如果输出nginx: configuration file /etc/nginx/nginx.conf test is successful,说明配置无语法错误。

  1. 重启Nginx使配置生效:
sudo systemctl restart nginx

进一步排查手段

如果修正后仍有问题,通过以下方式定位:

  • 查看Nginx访问日志,确认请求路径和转发情况:
tail -f /var/log/nginx/access.log

日志中会显示请求的URI和upstream_response_time,可以看到Nginx是否正确转发了请求。

  • 查看Nginx错误日志,排查权限或连接问题:
tail -f /var/log/nginx/error.log
  • 测试转发后的路径是否正确:在服务器上执行curl http://localhost:3001/login(对应你的路由),确认后端服务正常响应;再执行curl example.com/api/login,对比两者的响应差异。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 15:52:18