skip to content

Behind a TLS-terminating proxy, why does a FastAPI app run with fastapi run redirect /items to an http:// URL, and what fixes it?

level: middleimportance: should knowfreq 35%

answer

  1. the proxy speaks plain HTTP inward
  2. scheme comes from the ASGI scope
  3. X-Forwarded-Proto is only trusted sometimes
  4. default trust is loopback only

basics

~10 s

The proxy reaches Uvicorn over plain HTTP, so the request's scheme is http unless Uvicorn trusts the proxy's X-Forwarded-Proto. It trusts only 127.0.0.1 and ::1 by default; list the proxy's address in --forwarded-allow-ips.

solid answer

~40 s

Starlette builds a redirect URL from the ASGI scope's `scheme`, the `Host` header and the path. Behind a TLS-terminating proxy the connection into Uvicorn is plain HTTP, so `scheme` is `http` unless Uvicorn's proxy-header handling rewrites it from `X-Forwarded-Proto`. That handling is on by default (`--proxy-headers`) but only applies to peers listed in `--forwarded-allow-ips`, which defaults to `$FORWARDED_ALLOW_IPS` or `127.0.0.1,::1`. A proxy on the same host over loopback works; a proxy in another container or host is ignored, so the trailing-slash redirect for `/items` points at `http://example.com/items/`. Fix it with `fastapi run --forwarded-allow-ips="10.0.0.2"` (or the proxy's network). The same cause makes `HTTPSRedirectMiddleware` loop.

code

python · 23 lines
python
from fastapi import FastAPI
from fastapi.testclient import TestClient
from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware

app = FastAPI()


@app.get("/items/")
def list_items():
    return []


def location(trusted_hosts: str) -> str:
    # Uvicorn wraps the app like this; the TLS proxy connects from 10.0.0.2.
    wrapped = ProxyHeadersMiddleware(app, trusted_hosts=trusted_hosts)
    client = TestClient(wrapped, base_url="http://example.com", client=("10.0.0.2", 4000),
                        follow_redirects=False)
    r = client.get("/items", headers={"X-Forwarded-Proto": "https"})
    return f"{r.status_code} {r.headers['location']}"


print(location("127.0.0.1,::1"))  # 307 http://example.com/items/
print(location("10.0.0.2"))  # 307 https://example.com/items/

go deeper

for a junior

Remember that the proxy talks plain HTTP to the app, so the app must be told to trust the proxy's X-Forwarded-Proto header.

for a middle

Explain the two settings: --proxy-headers is on by default, and --forwarded-allow-ips decides whose headers count, defaulting to loopback only.

for a senior

Diagnose from the Location header and the peer address in the access log, and explain why HTTPSRedirectMiddleware loops behind an untrusted TLS proxy.

for a principal

Decide where redirects to HTTPS live (the proxy, not each app) and make the trusted proxy range part of the platform's start command.

## The setup A **TLS-terminating proxy** accepts HTTPS from clients, decrypts it and forwards the request to the application server over plain HTTP. FastAPI, through Starlette, decides the scheme of any URL it builds from the ASGI scope's `scheme` field, which Uvicorn sets from the connection it accepted, so behind such a proxy it starts out as `http`. Several things build absolute URLs from the scope: - Starlette's **trailing-slash redirect**: a request for `/items` when only `/items/` is declared is answered with a `307` to the slash form; - `request.url` and `request.url_for(...)`; - Starlette's `HTTPSRedirectMiddleware`, which redirects any `http` request to `https`. ## How Uvicorn learns the original scheme The proxy adds `X-Forwarded-Proto: https` (and `X-Forwarded-For` with the client's address). Uvicorn wraps the app in its `ProxyHeadersMiddleware`, which rewrites `scope["scheme"]` from `X-Forwarded-Proto` and `scope["client"]` from `X-Forwarded-For`, but **only when the connecting peer is trusted**. | Setting | Default with `fastapi run` | What it controls | |---|---|---| | `--proxy-headers` / `--no-proxy-headers` | on | whether the middleware is installed at all | | `--forwarded-allow-ips` | `$FORWARDED_ALLOW_IPS`, else `127.0.0.1,::1` | which peers' forwarded headers are believed | So the default trusts only **loopback**. That is why the same app redirects correctly on a single machine where the proxy connects over `127.0.0.1`, and to `http://` once the proxy runs in another container and connects from a private address. The header is still there; Uvicorn ignores it because the sender is not trusted. Other details of the middleware that matter here: - it accepts only `http`, `https`, `ws` and `wss` as `X-Forwarded-Proto` values, mapping them to `ws`/`wss` for WebSocket requests; - it does **not** read `X-Forwarded-Host` or `X-Forwarded-Port`; the host and port in a built URL come from the `Host` header, so the proxy has to pass the public host through; - it leaves lifespan events alone. ## The fix 1. Find the address the proxy connects from (the peer address Uvicorn logs in its access log). 2. Start the server trusting it: `fastapi run --forwarded-allow-ips="10.0.0.2"`, or a network such as `--forwarded-allow-ips="10.0.0.0/8"`, or set `FORWARDED_ALLOW_IPS` in the environment. 3. Leave `--proxy-headers` alone; it is already on. Advice to "set `--proxy-headers`", which appears even on FastAPI's own proxy page, names a flag that changes nothing unless the peer is trusted. 4. Confirm: request `https://example.com/api/v1/items` and read the `Location` header of the `307`. `--forwarded-allow-ips="*"` also makes the redirect right, and FastAPI's docs suggest it when nothing but the proxy can reach the server. It trusts every peer for the client address too, which is a separate risk. ## Checking what Uvicorn reports A short path operation shows what the app believes, which is faster than reading proxy configuration: ```python @app.get("/debug/origin") def origin(request: Request): return {"scheme": request.url.scheme, "client": request.client.host} ``` Call it through the proxy. If `scheme` is `http` and `client` is the proxy's own address, either the proxy sent neither header or Uvicorn did not trust it; untrusted, both headers are ignored together, because trust is decided once per connecting peer. If `scheme` is `https` but `client` is still the proxy, the proxy is most likely sending `X-Forwarded-Proto` without `X-Forwarded-For`. Remove the route once the deployment is verified; it reports client addresses to anyone who calls it. The trailing-slash redirect is usually the first symptom because it is the most common absolute URL FastAPI builds without being asked. `redirect_slashes` is on by default, so any client that calls `/items` instead of `/items/` receives a `307` with a `Location` built from the scope, and a browser following it to `http://` either fails or is sent back to `https://` by the proxy. ## The HTTPSRedirectMiddleware loop `HTTPSRedirectMiddleware` answers any request whose scope scheme is `http` (or `ws`) and that has a usable host with a `307` to the `https` (or `wss`) URL. Behind an untrusted TLS proxy, every request has scheme `http`, including the one that followed the redirect, so the browser loops until it gives up. Two fixes: - trust the proxy, so the scheme becomes `https` and the middleware passes the request on; - or remove the middleware, because the proxy already owns the HTTP-to-HTTPS redirect for clients. How middleware is ordered and configured is covered with FastAPI's middleware; here the point is that the middleware is only as right as the scheme Uvicorn reports.

  • Why did the redirect work on a single VM and break when the proxy moved into its own container?
    On the VM the proxy connected over `127.0.0.1`, which is in Uvicorn's default `--forwarded-allow-ips` of `127.0.0.1,::1`, so `X-Forwarded-Proto` was honoured. In a container network the proxy connects from a private address that is not trusted, so the header is ignored and the scheme stays `http`.
  • The scheme is now https, but redirects point at an internal host name. What is wrong?
    Uvicorn's middleware does not read `X-Forwarded-Host`; Starlette takes the host for built URLs from the `Host` header. The proxy is forwarding its own upstream name as `Host` and needs to pass the client's original `Host` through. That is proxy configuration, not a FastAPI setting.

The proxy is a receptionist who answers the secure outside line and relays each call on an internal phone. Unless you trust her note saying the call came in on the secure line, every call looks internal to you.

  • Thinks passing --proxy-headers alone makes Uvicorn trust the proxy
  • Believes Uvicorn trusts forwarded headers from any address by default
  • Expects Uvicorn to take the redirect host from X-Forwarded-Host
  • Adds HTTPSRedirectMiddleware behind a TLS proxy without trusting its headers