FastAPI应用混合内容问题:部分端点无法通过HTTPS正常访问
FastAPI应用混合内容问题:部分端点无法通过HTTPS正常访问
最近我维护一个FastAPI+React的项目时,碰到了个特别费解的混合内容问题——明明整个站点是通过HTTPS加载的,但偏偏有个别API端点会被浏览器以HTTP请求,直接触发安全拦截错误,折腾了好一阵都没找到根因,先把情况整理出来:
问题现象
页面本身能正常通过HTTPS加载,但像/categorias/这类特定端点会被浏览器发起HTTP请求,触发如下混合内容拦截提示:
Mixed content: load all resources via HTTPS to improve the security of your site
1 resource Name: categorias/
Restriction Status: blocked
奇怪的是,另一些端点比如/whitelist/却能完全正常走HTTPS,没有任何问题。
我的环境配置
- 前端:React,使用fetch进行API调用
- 后端:FastAPI
- 部署方式:VPS + Coolify + Docker
- API基础URL已经正确配置为HTTPS地址
我试过的排查步骤
我已经逐一排查了这些可能的点,但都没找到问题根源:
- 检查了所有前端代码,确保没有硬编码的HTTP格式URL
- 确认所有API调用都统一使用了配置好HTTPS的
API_URL常量 - 清空过浏览器缓存,排除旧缓存的影响
- 对比了正常工作的
whitelist路由和出问题的categorias路由配置,两者看起来完全一致 - 检查了不同端点间的CORS配置,没有发现差异
相关代码
出问题的Categorias路由
router = APIRouter(prefix="/categorias", tags=["Categorias"]) @router.get("/", response_model=list[Categoria]) def listar_categorias( session: Session = Depends(get_session), tenant_id: str = Depends(get_tenant_id) ): categorias = session.exec( select(Categoria).where(Categoria.tenant_id == tenant_id) ).all() return categorias
更新:找到临时Workaround,但仍未明确根因
目前还没搞清楚为什么只有特定端点会出现这个问题,不过找到了一个临时解决办法——给FastAPI加一个HTTP中间件,自动把响应中的HTTP重定向地址替换为HTTPS:
@app.middleware("http") async def rewrite_http_to_https(request, call_next): response = await call_next(request) # 检查响应是否为重定向类型 if response.status_code in [301, 302, 303, 307, 308] and "location" in response.headers: if response.headers["location"].startswith("http:"): response.headers["location"] = response.headers["location"].replace("http:", "https:", 1) return response
内容来源于stack exchange
相关产品推荐
相关产品推荐

