EC2上FastAPI root_path与Nginx配置404问题排查
解决FastAPI + Nginx部署中/api路径返回404的问题
问题根源
你设置FastAPI的root_path="/api"后,FastAPI会将/api视为请求的基础路径——也就是说,它期望实际传入的请求路径是/api之后的部分。但当前Nginx配置里,location /api会把请求路径/api原样转发到FastAPI的8000端口,此时FastAPI收到的请求路径是/api,而你的路由是/,两者不匹配,自然返回404。
可行解决方案
方案1:调整Nginx代理配置(推荐)
修改Nginx中location /api的配置,在proxy_pass末尾添加斜杠,同时补充必要的请求头:
location /api { proxy_pass http://127.0.0.1:8000/; # 关键:末尾添加斜杠 proxy_http_version 1.1; 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; }
添加斜杠后,Nginx会把/api后面的路径(包括空路径)转发到FastAPI的根路径。比如请求mydomain/api时,实际转发到FastAPI的路径是/,刚好匹配你定义的@app.get("/")路由。
方案2:调整FastAPI的root_path配置
如果不想修改Nginx,可以调整FastAPI的root_path设置方式:
- 先移除代码里的
root_path参数:
from fastapi import FastAPI, Request app = FastAPI() # 删掉root_path="/api" @app.get("/") async def base(request: Request): return {"message": "Hello World", "root_path": request.scope.get("root_path")}
- 启动uvicorn时通过命令行指定root_path:
uvicorn main:app --reload --root-path /api
同时保持Nginx的proxy_pass为http://127.0.0.1:8000(不要加斜杠),这样Nginx转发/api到FastAPI的/api路径,而FastAPI会把/api当作基础路径,匹配内部的/路由。
验证步骤
重启Nginx(sudo systemctl restart nginx)和FastAPI服务后,请求mydomain/api,应该能收到包含"message": "Hello World"的正常响应。
内容的提问来源于stack exchange,提问作者Yoav Katzman
相关产品推荐
相关产品推荐

