Nginx反向代理FastAPI Swagger文档路径返回404问题排查
问题根因
返回404和后端地址错误无关,核心是两个配置逻辑问题:
- Nginx
proxy_pass路径拼接规则踩坑 - FastAPI Swagger文档的资源加载逻辑和普通业务接口不同,需要额外适配前缀
你当前配置里/p1/、/p2/能正常生效,是因为这两个路径的proxy_pass只写了服务地址+端口,没有附带子路径,Nginx会把请求的完整路径直接转发给后端,刚好匹配后端服务的根路由。而/ali/对应的proxy_pass写了http://172.17.0.1:8020/api/docs且末尾没有加斜杠,访问localhost:8080/ali/时,Nginx实际转发给后端的路径是http://172.17.0.1:8020/api/docs/ali/,FastAPI没有注册这个路由,直接返回404。
另外你贴的原始配置存在语法问题:缺少http块包裹,末尾多了一个多余的闭合花括号,修改配置时需要先修正结构,否则重载会报错。
排查步骤
先排除后端连通性问题:
- 进入Nginx所在运行环境(容器/主机),执行
curl http://172.17.0.1:8020/api/docs - 如果命令能正常返回Swagger页面的HTML内容,说明后端服务地址、端口、访问权限都正常,不需要调整FastAPI服务的监听配置
- 如果curl返回连接拒绝/404,先检查FastAPI服务是否绑定
0.0.0.0地址(Docker环境下172.17.0.1是宿主机网关地址,服务绑定127.0.0.1时容器内无法访问)
可行解决方案
根据实际需求二选一即可:
方案1:仅将localhost:8080/ali/映射到Swagger文档页
不需要修改FastAPI代码,直接调整Nginx配置即可,注意配置里的斜杠不要漏写:
http { # 保留你原来的user、worker、events等全局配置 server { client_max_body_size 500M; proxy_connect_timeout 600; proxy_send_timeout 600; proxy_read_timeout 600; send_timeout 600; client_body_timeout 600; listen 8080; resolver 127.0.0.11; autoindex off; server_name localhost; server_tokens off; # 处理不带尾斜杠的访问,自动补全斜杠避免路径错误 location = /ali { return 302 /ali/; } location /ali/ { # 末尾必须加斜杠,确保路径拼接正确 proxy_pass http://172.17.0.1:8020/api/docs/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # 替换响应内容里的资源路径,避免从根路径加载js/css、openapi.json导致404 sub_filter 'href="/' 'href="/ali/'; sub_filter 'src="/' 'src="/ali/'; sub_filter 'url("/' 'url("/ali/'; sub_filter '/openapi.json' '/ali/openapi.json'; sub_filter_once off; } # 单独代理Swagger依赖的openapi接口和静态资源 location /ali/openapi.json { proxy_pass http://172.17.0.1:8020/openapi.json; } location /ali/docs/ { proxy_pass http://172.17.0.1:8020/docs/; } # 保留你原来的/p1/、/p2/配置 location /p1/ { proxy_pass http://172.17.0.1:80; } location /p2/ { proxy_pass http://172.17.0.1:49159; } } }
修改完成后执行nginx -t验证语法,通过后执行nginx -s reload重载配置即可生效。
方案2:将整个FastAPI服务挂载到/ali/路径下(推荐,稳定性更高)
如果需要在/ali/路径下访问所有FastAPI接口,不只是Swagger文档,用这个方案不会出现静态资源加载异常的问题:
- 修改FastAPI初始化代码,添加
root_path参数适配反向代理前缀:
修改后重启FastAPI服务,框架会自动适配前缀,Swagger的资源路径、接口调试路径都会自动带上/ali前缀,不需要额外做响应内容替换。from fastapi import FastAPI # 配置root_path和Nginx代理前缀一致 app = FastAPI(root_path="/ali") - Nginx配置简化为:
重载Nginx后,访问location /ali/ { proxy_pass http://172.17.0.1:8020/; 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-Prefix /ali; }localhost:8080/ali/api/docs即可正常打开Swagger文档,所有接口都可以正常调试。
内容的提问来源于stack exchange,提问作者amd
相关产品推荐
相关产品推荐

