An App Behind a TLS-Terminating Proxy Builds http URLs Unless It Trusts Forwarded Headers
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-headersmakes Uvicorn useX-Forwarded-ProtoandX-Forwarded-For.--forwarded-allow-ipslists the proxies whose headers are trusted. Gunicorn has the sameforwarded_allow_ipssetting; Django usesSECURE_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
- Docker and Container Security MOC - hub for Docker notes.
- One Shared Reverse Proxy Can Route Many Compose Projects by Host Name - the proxy setup that terminates TLS.
- Per-IP Rate Limiting Behind a Reverse Proxy in Django - choosing which forwarded IP to trust.
- Uvicorn documentation: Settings, HTTP -
--proxy-headersand--forwarded-allow-ips. - MDN: X-Forwarded-Proto - the header and its purpose.
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.