TrustedHostMiddleware
TheTrustedHostMiddleware enforces that all incoming requests have a correctly set Host header to protect against Host header attacks. Any request with a non-matching Host header will result in a 400 Bad Request response.
Usage
Parameters
list[str]
required
A list of allowed hostnames. Wildcard domains are supported using
* prefix. For example:"example.com"- Exact match only"*.example.com"- Matches any subdomain of example.com"*"- Allows any hostname (not recommended for production)
bool
default:"True"
If
True, requests to non-www versions of allowed hosts will be redirected to their www equivalent. For example, example.com redirects to www.example.com.How It Works
The middleware:- Extracts the
Hostheader from incoming requests - Checks if the host matches any entry in
allowed_hosts - Returns a 400 Bad Request response if the host is not allowed
- Optionally redirects to www version if
www_redirect=True
Examples
Basic Configuration
Wildcard Subdomains
Development and Production
Multiple Domains
Security Considerations
- Always use in production: Host header attacks can lead to password reset poisoning, cache poisoning, and other vulnerabilities
- Avoid wildcards: Use specific hostnames when possible; avoid
["*"]in production - Include all valid hosts: Ensure all legitimate access points are included (www, api, subdomains)
- Load balancers: If behind a proxy, ensure the proxy forwards the original Host header