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

NGINX反向代理SPA与API时API路由返回404问题排查

问题:NGINX反向代理API请求返回404的排查

当前环境配置:

  • NextJs SPA运行在localhost:3000
  • AspNetCore API运行在localhost:55379

为解决跨域问题配置了NGINX反向代理,nginx.conf配置如下:

server {
        listen       80;
        server_name  localhost;

        location / {
            proxy_pass http://localhost:3000;
        }

        location ^~ /api/ {
            proxy_pass http://localhost:55379;
        }   
    }

NextJs应用可通过http://localhost正常访问,但API请求返回404。例如SPA调用登录路由http://localhost/api/user/Login,该请求应代理到http://localhost:55379/api/user/Login,但始终无法到达API,请求返回404。请问该配置中遗漏了什么?


解决方案

问题核心在于NGINX的proxy_pass路径拼接逻辑:
当proxy_pass的目标URL末尾没有斜杠时,NGINX会把完整的匹配路径(包括/api/前缀)拼接到目标URL后。但如果你的AspNetCore API实际路由不包含/api前缀(比如接口真实地址是http://localhost:55379/user/Login),就会导致404。

修复方案1:适配无/api前缀的API

修改proxy_pass,在目标URL末尾添加斜杠:

location ^~ /api/ {
    proxy_pass http://localhost:55379/;
}

此时http://localhost/api/user/Login会被转发为http://localhost:55379/user/Login,匹配API的真实路由。

修复方案2:适配有/api前缀的API

如果你的API确实配置了/api前缀(比如AspNetCore中使用[Route("api/[controller]")]),则需要补充代理请求头,确保API能正确解析请求:

location ^~ /api/ {
    proxy_pass http://localhost:55379;
    # 传递必要的请求头,避免API因头信息缺失导致路由解析错误
    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;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 20:52:08