FastAPI+Apache部署:静态文件无法通过HTTPS访问问题求助
解决FastAPI+Apache部署的混合内容错误
核心原因
Apache反向代理将外部HTTPS请求转发给本地HTTP的FastAPI服务时,FastAPI未识别到外部请求的真实协议(HTTPS)和主机域名,导致生成的静态资源URL使用http://localhost:3000而非HTTPS域名,触发混合内容错误。
解决方案步骤
1. 配置FastAPI信任反向代理头
修改FastAPI代码,添加中间件识别反向代理传递的协议和主机信息:
from fastapi import FastAPI, Request from fastapi.responses import HTMLResponse from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates from starlette.middleware.forwarded import ForwardedHeadersMiddleware # 初始化FastAPI,root_path对应Apache反向代理的路径(根路径填"/") app = FastAPI(root_path="/") # 添加中间件,信任代理传递的转发头,生产环境建议替换"*"为你的域名 app.add_middleware(ForwardedHeadersMiddleware, trusted_hosts=["*"]) templates = Jinja2Templates(directory="templates/") app.mount("/static", StaticFiles(directory="static"), name="static") @app.get("/home/", response_class=HTMLResponse) async def home(request: Request): return templates.TemplateResponse("home.html", {"request": request})
2. 更新Apache反向代理配置
确保Apache在转发请求时传递必要的头信息,让FastAPI知晓外部请求的真实协议和主机:
<VirtualHost *:443> ServerName www.your-domain.com # 已有的SSL证书配置 SSLEngine on SSLCertificateFile /path/to/your/cert.pem SSLCertificateKeyFile /path/to/your/privkey.pem # 反向代理到FastAPI服务 ProxyPass / http://localhost:3000/ ProxyPassReverse / http://localhost:3000/ # 传递关键头信息 RequestHeader set X-Forwarded-Proto "https" RequestHeader set X-Forwarded-Host "www.your-domain.com" RequestHeader set X-Forwarded-Port "443" # 其他常规配置... </VirtualHost>
3. 修正模板中的静态资源链接
在Jinja2模板中使用url_for生成静态资源URL,避免硬编码:
<!-- 正确写法 --> <img src="{{ url_for('static', path='logo.png') }}" alt="Site Logo"> <!-- 错误写法(直接硬编码localhost),需移除 --> <!-- <img src="http://localhost:3000/static/logo.png" alt="Site Logo"> -->
内容的提问来源于stack exchange,提问作者Blake A
相关产品推荐
相关产品推荐

