FastAPI 部署在非根目录的注意点

解决方案:设置 root_path

FastAPI 提供了 root_path 参数,告诉它你的应用实际挂载在子目录,这样它生成的文档路径和请求路径都会自动加上这个前缀。


具体做法

假设你的服务挂载在子目录 /api 下,启动 FastAPI 时:

from fastapi import FastAPI

app = FastAPI(root_path="/api")

@app.get("/")
async def root():
    return {"message": "Hello from /api"}

然后你访问:

  • http://yourdomain.com/api/docs
  • http://yourdomain.com/api/openapi.json

这样 FastAPI 的文档请求和资源路径都会带上 /api,不会再出现找不到定义文件的问题。


如果你用的是反向代理(比如 Nginx)

Nginx 配置中转时,也要把 /api 转发给后端:

location /api/ {
    proxy_pass http://127.0.0.1:53001/;
    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;
}

确保请求路径和 FastAPI root_path 配置一致。


参考启动命令(用 uvicorn)

uvicorn app.app:app --host 0.0.0.0 --port 53001

代码里设置 root_path="/api"

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇