添加反向代理协议头中间件,支持 Nginx/Traefik 后正确识别 HTTPS 请求

This commit is contained in:
puke
2025-12-06 13:41:18 +08:00
parent 22ee68d005
commit c83e905c63

View File

@@ -34,7 +34,7 @@ if str(_project_root) not in sys.path:
import argparse
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from loguru import logger
@@ -108,6 +108,24 @@ app = FastAPI(
lifespan=lifespan,
)
# Add middleware for handling reverse proxy headers (Nginx/Traefik)
@app.middleware("http")
async def handle_forwarded_proto(request: Request, call_next):
"""
Handle X-Forwarded-Proto header from reverse proxy
This ensures that request.base_url returns the correct protocol (https)
when the application is behind a reverse proxy like Nginx or Traefik.
"""
# Check for X-Forwarded-Proto header (standard)
forwarded_proto = request.headers.get("x-forwarded-proto")
if forwarded_proto:
# Update the request scheme
request.scope["scheme"] = forwarded_proto
response = await call_next(request)
return response
# Add CORS middleware
if api_config.cors_enabled:
app.add_middleware(