---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

# 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`** (`django/core/exceptions.py:DisallowedHost`) inside `HttpRequest.get_host`, and **`SecurityMiddleware`** (`django/middleware/security.py:SecurityMiddleware`) at the very outer rim of the middleware onion.

## `ALLOWED_HOSTS` is lazy — until `CommonMiddleware` trips it

Open `HttpRequest.get_host` (`django/http/request.py:HttpRequest.get_host`) alongside `split_domain_port` (`django/http/request.py:split_domain_port`) and `validate_host` (`django/http/request.py:validate_host`).

```python
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` (`django/http/request.py: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)` (`django/utils/http.py:is_same_domain`), 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` (`django/middleware/common.py:CommonMiddleware.process_request`):

```python
# 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`, `django/core/exceptions.py:SuspiciousOperation`) escapes from `CommonMiddleware` — or earlier from `SecurityMiddleware` when building an SSL redirect — Chapter 3's `response_for_exception` (`django/core/handlers/exception.py: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`:

```text recording=ch05-security
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):
- If `SECURE_SSL_REDIRECT` is `True`, `HttpRequest.is_secure` returns `False`, and the stripped request path matches none of `SECURE_REDIRECT_EXEMPT`, it picks `SECURE_SSL_HOST` or calls `HttpRequest.get_host` and short-circuits with `HttpResponsePermanentRedirect` (`301`) to `"https://<host><full_path>"`.
- Because `SecurityMiddleware` sits first in `MIDDLEWARE`, a plain-HTTP request never wakes sessions, authentication, URL resolution, or database connections; it bounces straight back to HTTPS — *and* notice that if `SECURE_SSL_HOST` is unset, calling `HttpRequest.get_host` validates `ALLOWED_HOSTS` before redirecting so an attacker cannot use your redirector as an open bounce to `https://evil.example/`.

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:
- `"Strict-Transport-Security"` (`"max-age=<N>"`, plus optional `"includeSubDomains"` and `"preload"`) — written **only when `HttpRequest.is_secure` is `True`** and `SECURE_HSTS_SECONDS` is non-zero, matching RFC 6797 (browsers must ignore HSTS sent over plain HTTP).
- `"X-Content-Type-Options: nosniff"` (enabled by default in Django `6.1`: `SECURE_CONTENT_TYPE_NOSNIFF = True`).
- `"Referrer-Policy"` (defaults to `"same-origin"` in Django `6.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._get_scheme` sees `"wsgi.url_scheme" == "http"` on **every** request.

Open `HttpRequest.scheme` (`django/http/request.py:HttpRequest.scheme`):

```python
@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:

```text recording=ch05-security
  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

- **Removing `CommonMiddleware` silently disables `ALLOWED_HOSTS` on views that never call `get_host()`.** Minimal API stacks that strip `MIDDLEWARE` down to two items often assume `ALLOWED_HOSTS` is checked in the WSGI handler. It is not — either keep `CommonMiddleware` or validate hosts explicitly at the proxy and in middleware.
- **`SecurityMiddleware` caches settings once in `__init__`.** Notice lines 11–19 of `django/middleware/security.py`: mutating `settings.SECURE_SSL_REDIRECT` at runtime after the middleware chain was constructed has no effect unless the handler rebuilds `_middleware_chain` (which `@override_settings` triggers via the `setting_changed` signal in tests).
- **Never point `SECURE_PROXY_SSL_HEADER` at 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](csrf.md).
