Django 6.1.3

5.1 Security by default

Allowed hosts, redirects, and proxy headers

Where does HttpRequest.get_host 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.build_absolute_uri 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.get_host, and SecurityMiddleware at the very outer rim of the middleware onion.

ALLOWED_HOSTS is lazy — until CommonMiddleware trips it

Open HttpRequest.get_host 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:

  1. HttpRequest._get_raw_host checks META["HTTP_X_FORWARDED_HOST"] first only when USE_X_FORWARDED_HOST is True, then META["HTTP_HOST"], and finally falls back to "SERVER_NAME" + get_port().
  2. split_domain_port matches 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. Then validate_host checks pattern == "*" or is_same_domain(host, pattern), where a leading dot like ".desk.example" matches both the apex domain and any subdomain.
  3. Nothing inside WSGIHandler, ASGIHandler, or HttpRequest.__init__ calls get_host() automatically. Validation is completely lazy!

Wait — then why does a standard Django project still reject "Host: evil.example" with 400 Bad Request on a plain view that never calls get_host()?

Look at line 48 of CommonMiddleware.process_request:

# 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.get_host 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.security.DisallowedHost", 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:

Recorded on Django 6.1.3 ch05-security script
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.example". 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/middleware/security.py — the entire class is only 66 lines long, yet it guards two halves of every request (SecurityMiddleware.process_request and SecurityMiddleware.process_response).

At startup (SecurityMiddleware.__init__, 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.process_request, lines 21–31):

On the response path (SecurityMiddleware.process_response, lines 33–66), it stamps up to four browser hardening headers using setdefault so views can override any of them deliberately:

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._get_scheme sees "wsgi.url_scheme" == "http" on every request.

Open HttpRequest.scheme:

@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.url_scheme = "http" plus "HTTP_X_FORWARDED_PROTO": "https") with and without SECURE_PROXY_SSL_HEADER configured:

Recorded on Django 6.1.3 ch05-security script
  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:

  1. Without SECURE_PROXY_SSL_HEADER: Django ignores X-Forwarded-Proto, thinks the already-HTTPS user arrived over plain HTTP, and returns 301 Moved Permanently pointing to the exact same https://desk.example/wire/status/ URL — an infinite redirect loop in the browser — while also omitting "Strict-Transport-Security"!
  2. With SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https"): HttpRequest.is_secure flips to True, the request reaches the view (200 OK), and SecurityMiddleware emits all four headers including HSTS.
  3. Look at line 325 of request.py (str.split(",", 1)) and the third trace line: Django checks the leftmost comma-separated value ("https, http" evaluates to is_secure=True!). Why does that matter? If your reverse proxy appends to a client-supplied X-Forwarded-Proto header instead of stripping and overwriting it, a plain-HTTP attacker who sends X-Forwarded-Proto: https gets forwarded as "https, http" — and Django trusts the attacker’s leftmost "https", bypassing SECURE_SSL_REDIRECT and confusing CSRF’s HTTPS checks!

Where host and transport shields leak

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.