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