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

Windows10下Nginx配置多Spring Boot API同端口不同路径代理问题

解决Nginx同一域名端口下路径转发Spring Boot服务的问题

你的配置问题出在proxy_pass的路径处理上:当proxy_pass末尾不加斜杠时,Nginx会把请求的完整URI(包括/users或/inventory前缀)转发到后端服务,而如果你的Spring Boot API没有对应的前缀路径,就会出现无法匹配接口的情况。

方法1:调整proxy_pass路径(无需修改Spring Boot服务)

修改Nginx配置,在proxy_pass的URL末尾添加斜杠,这样Nginx会自动去掉location匹配的前缀,只转发剩余路径:

server{
    listen          80;
    server_name     localhost;

    location /users {
        proxy_pass http://localhost:8080/;
        # 可选:添加代理头,保证后端服务能获取正确的请求元数据
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    location /inventory {
        proxy_pass http://localhost:8081/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

方法2:给Spring Boot服务添加上下文路径(需修改服务配置)

如果允许调整Spring Boot服务,可以给每个服务设置对应的上下文路径,原配置即可正常工作:

  • 8080端口服务的配置文件(application.properties/application.yml)添加:
    server.servlet.context-path=/users
    
  • 8081端口服务添加:
    server.servlet.context-path=/inventory
    

验证步骤

  1. 修改配置后,进入Windows下Nginx安装目录,执行nginx -s reload重启Nginx使配置生效
  2. 测试请求:
    • 访问localhost/users/xxx会转发到http://localhost:8080/xxx(方法1)或http://localhost:8080/users/xxx(方法2)
    • 访问localhost/inventory/xxx会转发到http://localhost:8081/xxx(方法1)或http://localhost:8081/inventory/xxx(方法2)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 09:12:13