Allowed hosts, redirects, and proxy headers
Where does HttpRequest validate ALLOWED_HOSTS, and why do reverse proxies break HTTPS detection unless SECURE_PROXY_SSL_HEADER is configured carefully?
Before Django knows who the user is or what URL pattern matched, a request arrives carrying two untrusted network claims: the "Host" header (which domain the client thinks it reached) and whether the connection arrived over TLS. If an attacker can poison "Host" on a password-reset view, HttpRequest emails the victim a reset link pointing straight at "evil.example". If Django thinks an HTTPS request arrived over plain HTTP, every redirect and Strict-Transport-Security header misfires.
Django protects those two boundaries with DisallowedHost inside HttpRequest, and SecurityMiddleware at the very outer rim of the middleware onion.
ALLOWED_HOSTS is lazy — until CommonMiddleware trips it
Open HttpRequest alongside split_domain_port and validate_host.
def get_host(self):
host = self._get_raw_host()
allowed_hosts = settings.ALLOWED_HOSTS
if settings.DEBUG and not allowed_hosts:
allowed_hosts = [".localhost", "127.0.0.1", "[::1]"]
domain, port = split_domain_port(host)
if domain and validate_host(domain, allowed_hosts):
return host
else:
...
raise DisallowedHost(msg)
Notice three concrete facts in those twenty lines:
HttpRequestchecks._get_raw_host META["HTTP_X_FORWARDED_HOST"]first only whenUSE_X_FORWARDED_HOSTisTrue, thenMETA["HTTP_HOST"], and finally falls back to"SERVER_NAME"+get_port().split_domain_portmatches the lowercased host against RFC 1034/1035 (host_validation_re), strips any trailing DNS root dot ("desk.example."becomes"desk.example"), and rejects malformed hosts with an empty domain. Thenvalidate_hostcheckspattern == "*"oris_same_domain(host, pattern), where a leading dot like".desk.example"matches both the apex domain and any subdomain.- Nothing inside
WSGIHandler,ASGIHandler, orHttpRequestcalls.__init__ get_host()automatically. Validation is completely lazy!
Wait — then why does a standard Django project still reject "Host: evil with 400 Bad Request on a plain view that never calls get_host()?
Look at line 48 of CommonMiddleware:
# Check for a redirect based on settings.PREPEND_WWW
host = request.get_host()
if settings.PREPEND_WWW and host and not host.startswith("www."):
...
Even when PREPEND_WWW is False (the default!), CommonMiddleware evaluates HttpRequest unconditionally on every single request before the if branch. That single line acts as Django’s invisible ALLOWED_HOSTS tripwire. When DisallowedHost (a subclass of SuspiciousOperation, SuspiciousOperation) escapes from CommonMiddleware — or earlier from SecurityMiddleware when building an SSL redirect — Chapter 3’s response_for_exception intercepts it, logs to "django, and returns a 400 Bad Request before URL resolution or any view ever runs.
Watch that exact split happen live on Django 6.1.3:
ALLOWED_HOSTS, SecurityMiddleware redirects, and SECURE_PROXY_SSL_HEADER
MIDDLEWARE=[] Host='evil.example' on /quiet/ (no get_host) -> 200 OK (no host read)
MIDDLEWARE=[] Host='evil.example' on /host/ (calls get_host) -> 400 Bad Request logger=django.security.DisallowedHost
desk/ default stack Host='evil.example' on /wire/status/ (no get_host) -> 400 Bad Request
SECURE_SSL_REDIRECT=True Host='evil.example' -> 400 Bad Request (SecurityMiddleware calls get_host -> django.security.DisallowedHost)
With MIDDLEWARE = [], a view that never touches the host returns 200 OK to "Host: evil. The moment either the view calls get_host(), CommonMiddleware sits in MIDDLEWARE, or SecurityMiddleware redirects HTTP to HTTPS, DisallowedHost fires and turns the request into 400 Bad Request.
Inside SecurityMiddleware
Open django/ — the entire class is only 66 lines long, yet it guards two halves of every request (SecurityMiddleware and SecurityMiddleware).
At startup (SecurityMiddleware, lines 9–19), it snapshots every "SECURE_*" setting onto instance attributes and pre-compiles SECURE_REDIRECT_EXEMPT regular expressions once.
On the request path (SecurityMiddleware, lines 21–31):
- If
SECURE_SSL_REDIRECTisTrue,HttpRequestreturns.is_secure False, and the stripped request path matches none ofSECURE_REDIRECT_EXEMPT, it picksSECURE_SSL_HOSTor callsHttpRequestand short-circuits with.get_host HttpResponsePermanentRedirect(301) to"https://.<host><full_path>" - Because
SecurityMiddlewaresits first inMIDDLEWARE, a plain-HTTP request never wakes sessions, authentication, URL resolution, or database connections; it bounces straight back to HTTPS — and notice that ifSECURE_SSL_HOSTis unset, callingHttpRequestvalidates.get_host ALLOWED_HOSTSbefore redirecting so an attacker cannot use your redirector as an open bounce tohttps://.evil .example/
On the response path (SecurityMiddleware, lines 33–66), it stamps up to four browser hardening headers using setdefault so views can override any of them deliberately:
"Strict-Transport-Security"("max-age=<N>", plus optional"includeSubDomains"and"preload") — written only whenHttpRequestis.is_secure TrueandSECURE_HSTS_SECONDSis non-zero, matching RFC 6797 (browsers must ignore HSTS sent over plain HTTP)."X-Content-Type-Options: nosniff"(enabled by default in Django6.1:SECURE_CONTENT_TYPE_NOSNIFF = True)."Referrer-Policy"(defaults to"same-origin"in Django6.1)."Cross-Origin-Opener-Policy"(defaults to"same-origin", isolating the browsing context group against Spectre-class cross-origin leaks).
Reverse proxies and the SECURE_PROXY_SSL_HEADER trap
In almost every production deployment, a reverse proxy or load balancer (nginx, Caddy, Cloudflare, AWS ALB) terminates TLS at the edge and forwards plain HTTP over a private socket to Gunicorn or Uvicorn. That means WSGIRequest sees "wsgi on every request.
Open HttpRequest:
@property
def scheme(self):
if settings.SECURE_PROXY_SSL_HEADER:
try:
header, secure_value = settings.SECURE_PROXY_SSL_HEADER
except ValueError:
raise ImproperlyConfigured(...)
header_value = self.META.get(header)
if header_value is not None:
header_value, *_ = header_value.split(",", 1)
return "https" if header_value.strip() == secure_value else "http"
return self._get_scheme()
Run the exact same proxied request (wsgi plus "HTTP_X_FORWARDED_PROTO": "https") with and without SECURE_PROXY_SSL_HEADER configured:
proxy HTTP + X-Forwarded-Proto=https (no SECURE_PROXY_SSL_HEADER) -> 301 Moved Permanently Location='https://desk.example/wire/status/' HSTS=None
proxy HTTP + SECURE_PROXY_SSL_HEADER -> 200 OK HSTS='max-age=31536000; includeSubDomains' nosniff='nosniff' Referrer='same-origin' COOP='same-origin'
X-Forwarded-Proto='https, http' -> request.scheme='https' is_secure=True
Look closely at all three lines:
- Without
SECURE_PROXY_SSL_HEADER: Django ignoresX-Forwarded-Proto, thinks the already-HTTPS user arrived over plain HTTP, and returns301 Moved Permanentlypointing to the exact samehttps://URL — an infinite redirect loop in the browser — while also omittingdesk .example/ wire/ status/ "Strict-Transport-Security"! - With
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https"):HttpRequestflips to.is_secure True, the request reaches the view (200 OK), andSecurityMiddlewareemits all four headers including HSTS. - Look at line 325 of
request.py(str) and the third trace line: Django checks the leftmost comma-separated value (.split(",", 1) "https, http"evaluates tois_secure=True!). Why does that matter? If your reverse proxy appends to a client-suppliedX-Forwarded-Protoheader instead of stripping and overwriting it, a plain-HTTP attacker who sendsX-Forwarded-Proto: httpsgets forwarded as"https, http"— and Django trusts the attacker’s leftmost"https", bypassingSECURE_SSL_REDIRECTand confusing CSRF’s HTTPS checks!
Where host and transport shields leak
- Removing
CommonMiddlewaresilently disablesALLOWED_HOSTSon views that never callget_host(). Minimal API stacks that stripMIDDLEWAREdown to two items often assumeALLOWED_HOSTSis checked in the WSGI handler. It is not — either keepCommonMiddlewareor validate hosts explicitly at the proxy and in middleware. SecurityMiddlewarecaches settings once in__init__. Notice lines 11–19 ofdjango/: mutatingmiddleware/ security .py settingsat runtime after the middleware chain was constructed has no effect unless the handler rebuilds.SECURE_SSL_REDIRECT _middleware_chain(which@override_settingstriggers via thesetting_changedsignal in tests).- Never point
SECURE_PROXY_SSL_HEADERat a header the proxy does not strip unconditionally. Configure your edge proxy to overwrite (never append to)X-Forwarded-Proto, and never expose the WSGI/ASGI application port directly to untrusted networks.
With host identity and HTTPS transport established, the next barrier inside the middleware onion stops cross-site forged state changes: CSRF tokens, masking, and origin checks.