FastAPI & Traefik: Jinja url_for is not Returning https [SOLVED]
Contents
Issue
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:
Error
Mixed Content: The page at 'https://automationd.com/' was loaded over HTTPS, but requested an insecure stylesheet 'http://automationd.com/static/css/main.css'. This request has been blocked; the content must be served over HTTPS.
Root Cause
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.
Solution
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.