Forums

HTTP to HTTPS redirect for ASGI FastAPI site

I have successfully implemented a FastAPI powered web site on Python Anywhere following the instructions for "Deploying ASGI sites on PythonAnywhere (beta)" but am experiencing a blocker due to HTTP>HTTPS redirect issues.

  • I've been able to implement HTTPS connections, however it still does not automatically redirect HTTP browser sessions to HTTPS. This is problematic because it circumvents data encryption, and more importantly for my use case, it breaks username/password authentication on my site unless users explicitly use HTTPS.
  • According to my engineering team, browsers silently refuse to send Secure cookies over HTTP — they don't report an error, they just omit the cookie entirely. So from the app's perspective, the request arrives with no session cookie, the app sees no authenticated user, and the login fails.
  • I've attempted to use the redirect middleware recommended in one of other forum discussions (https://fastapi.tiangolo.com/advanced/middleware/#httpsredirectmiddleware) but this fails with a ERR_TOO_MANY_REDIRECTS error. Again, according to my team, PythonAnywhere terminates TLS at the nginx layer. By the time a request reaches the FastAPI app, it always looks like http:// — even if the browser sent https://. So HTTPSRedirectMiddleware sees every request as HTTP and redirect it to HTTPS... which arrives at nginx as HTTPS... which arrives at my app as HTTP again, creating an infinite loop.

Please let me know if there is a way to do the redirect programmatically at the nginx layer or some other solution. If not I will not be able to use PA to host this site.

It sounds like you cannot use PythonAnywhere for your site

Agreed. I've found another provider. It was not hard to set up nginx to work properly on their platform. I'd suggest adding this feature to PythonAnywhere for ASGI as it seems FastAPI is a popular and fast growing platform for python web developers.