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

使用StaticFiles时,如何在FastAPI根路径加载非index.html文件?

问题原因

FastAPI中通过app.mount()挂载的静态文件服务路由优先级高于手动定义的@app.get("/")路由。当你把静态文件挂载在根路径"/"且开启html=True时,访问根路径会触发静态文件服务的自动索引功能,返回static目录下的index.html,而非你定义的路由返回的custom.html。

解决方法

提供两种可行解决方案,可根据需求选择:

方案1:调整静态文件挂载路径

将静态文件挂载到非根路径(比如/static),让手动定义的根路径路由正常生效:

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse

app = FastAPI()

# 静态文件挂载到/static路径
app.mount(
    "/static",
    StaticFiles(directory="static", html=True),
    name="static",
)

@app.get("/")
async def index() -> FileResponse:
    # media_type使用标准的text/html格式
    return FileResponse("custom.html", media_type="text/html")

方案2:自定义静态文件服务的索引页

如果需要保持静态文件挂载在根路径,可通过index_page参数指定根路径返回的自定义首页,无需手动定义路由:

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

app = FastAPI()

# 指定根路径返回static目录下的custom.html作为索引页
app.mount(
    "/",
    StaticFiles(directory="static", html=True, index_page="custom.html"),
    name="static",
)

这种方式要求custom.html文件放在static目录下,静态文件服务会自动处理根路径请求,返回你指定的页面。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 22:39:20