FastAPI & Traefik: Jinja url_for is not Returning https [SOLVED]

I’ve recently stumbled upon an issue where Jinja Template function url_for returned a url with http instead of https. It mainly caused security issues, which are typically manifested in a browser with an error:

Mixed Content: The page at '' was loaded over HTTPS, but requested an insecure stylesheet ''. This request has been blocked; the content must be served over HTTPS.

It appears that this is happening due to malfunctioning protocol detection. FastAPI “thinks” that it’s running under http. But why? There is an Issue for an underlying Starlette library.

Basically we need to make sure to start uvicorn with two parameters:

  • --proxy-headers
  • --forwarded-allow-ips=*

This way Uvicorn will be able to receive X-Forwareded-Proto (which would be set to https) and detect that it’s running behind an https proxy and needs to return url with https url scheme.

Second Head Post
This is a post from Second Head. So please, don’t expect too much.

Related Content