如何通过Docker-Compose为Traefik配置X-Forward*系列请求头?
解决方法
问题由两个配置缺失共同导致:Traefik未给HTTPS路由透传正确的X-Forward头,以及FastAPI运行环境未信任代理转发的头,修改步骤如下:
1. 调整docker-compose Traefik标签配置
你之前的配置错误点在于:将X-Forwarded-Proto配置在https-redirect中间件上,该中间件仅作用于HTTP跳转逻辑,不会生效到实际处理业务请求的HTTPS路由。
在fastapi服务的labels块中新增以下配置:
# 新增专门的头传递中间件,透传正确的原始请求信息 - traefik.http.middlewares.fastapi-proxy-headers.headers.customrequestheaders.X-Forwarded-Proto=https - traefik.http.middlewares.fastapi-proxy-headers.headers.customrequestheaders.X-Forwarded-Host=${WEBSITE_URL?Variable not set} # 将头传递中间件绑定到HTTPS路由 - traefik.http.routers.fastapi-https.middlewares=fastapi-proxy-headers
修改后完整的labels块参考:
labels: - traefik.enable=true - traefik.http.services.fastapi.loadbalancer.server.port=80 - traefik.http.routers.fastapi-http.entrypoints=http - traefik.http.routers.fastapi-http.rule=Host(`${WEBSITE_URL?Variable not set}`) - traefik.docker.network=traefik-public - traefik.http.routers.fastapi-https.entrypoints=https - traefik.http.routers.fastapi-https.rule=Host(`${WEBSITE_URL?Variable not set}`) - traefik.http.routers.fastapi-https.tls=true - traefik.http.routers.fastapi-https.tls.certresolver=le - traefik.http.middlewares.https-redirect.redirectscheme.scheme=https - traefik.http.middlewares.https-redirect.redirectscheme.permanent=true - traefik.http.routers.fastapi-http.middlewares=https-redirect # 新增的配置 - traefik.http.middlewares.fastapi-proxy-headers.headers.customrequestheaders.X-Forwarded-Proto=https - traefik.http.middlewares.fastapi-proxy-headers.headers.customrequestheaders.X-Forwarded-Host=${WEBSITE_URL?Variable not set} - traefik.http.routers.fastapi-https.middlewares=fastapi-proxy-headers
2. 调整FastAPI运行配置
默认Uvicorn/Starlette不会信任代理传递的X-Forward系列头,需要在启动命令中添加--forwarded-allow-ips参数,允许读取代理的转发信息:
uvicorn main:app --host 0.0.0.0 --port 80 --forwarded-allow-ips "*"
如果需要更高安全性,可以将*替换为Traefik所在的docker网段(可以通过docker network inspect traefik-public查看具体网段)。
如果使用Gunicorn+UvicornWorker部署,启动参数添加--forwarded-allow-ips "*"即可生效。
修改完成后重新启动容器,Jinja2渲染的url_for、request.url就会自动识别为HTTPS协议。
内容的提问来源于stack exchange,提问作者jonbon
相关产品推荐
相关产品推荐

