An App Behind a TLS-Terminating Proxy Builds http URLs Unless It Trusts Forwarded Headers

In progress Docker Networking AppSec

When a reverse proxy terminates TLS, the browser speaks HTTPS to the proxy and the proxy speaks plain HTTP to the app. The app therefore believes every request arrived over http:// from the proxy's IP. Anything it builds from the request (links from url_for(), redirects, the client IP in logs or rate limits) is wrong: pages load, then the browser blocks their CSS and scripts as mixed content.

What Gets Lost and What Restores It

Lost at the proxy Header the proxy adds
scheme (https) X-Forwarded-Proto: https
client IP X-Forwarded-For: <client>, <proxies...>
original port X-Forwarded-Port: 443

The app server must be told to read these headers and rewrite the request scope from them; by default it ignores them, because any client could send them.

Configuring the App Server

uvicorn main:app --host 0.0.0.0 --port 8000 \
  --proxy-headers --forwarded-allow-ips "172.18.0.2"
  • --proxy-headers makes Uvicorn use X-Forwarded-Proto and X-Forwarded-For.
  • --forwarded-allow-ips lists the proxies whose headers are trusted. Gunicorn has the same forwarded_allow_ips setting; Django uses SECURE_PROXY_SSL_HEADER.

In Templates

Build asset links with the framework's URL helper ({{ url_for('static', path='css/style.css') }} in Starlette/FastAPI) rather than hard-coded paths: once the scheme is right, the helper produces https:// links, and it also follows sub-path deployments.

References

Review cards

Flashcard Why does an app behind a TLS-terminating proxy build `http://` links?

The proxy talks plain HTTP to it, so every request seems to arrive over http from the proxy's IP. Links and redirects use that scheme, and the browser blocks the CSS and scripts as mixed content.

Flashcard How do you make Uvicorn use the scheme and client IP the proxy forwards, and why restrict it?

--proxy-headers reads X-Forwarded-Proto and X-Forwarded-For; --forwarded-allow-ips lists the proxies to trust. Trusting every IP lets clients forge their address unless the app is reachable only through the proxy.