I created a FastAPI app and I can access the Swagger UI autodocs at https://cloudrundomain.app/docs
. When I send an HTTPS request using the Swagger UI, the request.headers.get("X-Forwarded-Proto")
is HTTPS, but the request.url
is http://cloudrundomain
(the bottom of my problem is that HTTPException
is HTTP, but I think it starts there).
I don’t think it’s a good idea, but I tried doing what you could see below. The “Modify the scheme to HTTPS to avoid mixed content issues” triggers, but the redirection then fails.
@app.middleware("http")
async def force_https(request: Request, call_next):
# Check the X-Forwarded-Proto header to determine if the request is HTTP
forwarded_proto = request.headers.get("X-Forwarded-Proto")
if forwarded_proto == "http":
print("Redirect to HTTPS")
return RedirectResponse(url=f"https://{request.url.hostname}{request.url.path}")
# Ensure URLs are constructed using HTTPS
# Modify request.url to use HTTPS if necessary
if forwarded_proto == "https" and request.url.scheme == "http":
print("Modify the scheme to HTTPS to avoid mixed content issues")
return RedirectResponse(url=f"https://{request.url.hostname}{request.url.path}")
# Proceed with the request if it's already HTTPS or after the redirect
response = await call_next(request)
return response
I found a solution by referring to this GitHub issue: https://github.com/encode/uvicorn/issues/369.
To be more specific, I changed the way I was starting my FastAPI web app. Previously, I used:
fastapi run --workers 4 app/main.py
I switched to using directly Uvicorn with the following command:
uvicorn your_app:app --host 0.0.0.0 --port 8000 --proxy-headers --forwarded-allow-ips "*"
1