skip to Main Content

I have a html file and I configured the URL of the links as below.

app.mount("/static", StaticFiles(directory="static"), name="static")

{{ url_for('static', path='css/style.css') }}

I have got the domain creation for the application with nginx and haproxy.

When the html page is loaded the css and js stylings are not being loaded as it is using http instead of https.

Flask url_for generates http instead of https when running by docker

FastAPI links created by url_for in Jinja2 template use HTTP instead of HTTPS

I went with some of the links on similar issue but didn’t help as it is for html files.

When I hardcoded it worked. How can I make this static. I am using the uvicorn fastapi.

2

Answers


  1. One way to ensure that url_for always generates https URLs is to set the PREFERRED_URL_SCHEME configuration option to https in your application. This will instruct url_for to use the https scheme unless explicitly overridden. Here is an example:

    app = FastAPI()
    app.config["PREFERRED_URL_SCHEME"] = "https"
    
    Login or Signup to reply.
  2. In my case, FastAPI and uvicorn was behind reverse proxy on fly.io and have to add --proxy-headers and --forwarded-allow-ips '*' to my uvicorn command. Full example:

    uvicorn app:app --host 0.0.0.0 --port 8080 --proxy-headers --forwarded-allow-ips '66.241.124.179'
    

    To find IP address:

    ➜ fly ips list      
    VERSION IP                  TYPE            REGION  CREATED AT           
    v6      2a09:8280:1::1:de8b public          global  2023-02-11T11:24:14Z    
    v4      66.241.124.179      public (shared)     
    

    How it’s works?

    1. Uvicorn starts hanlding incomming request.
    2. If --proxy-headers is enabled, uvicorn pass proxy headers further:
      X-Forwarded-Proto, X-Forwarded-For, …
    3. Then uvicorn for incoming request trying to detect schema in ProxyHeadersMiddleware middleware
    4. In that middleware uvicorn parses client IP address from X-Forwarded-For header.
    5. Then compares that IP address to trusted list (--forwarded-allow-ips)
    6. If address is trusted, then extracts schema from X-Forwarded-Proto
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search