How to Use allowed_hosts in Django for Security
In Django,
ALLOWED_HOSTS is a list of strings representing the host/domain names your app can serve. You set it in your settings.py file to prevent HTTP Host header attacks by specifying allowed domains or IP addresses.Syntax
The ALLOWED_HOSTS setting is a list of strings in your settings.py file. Each string is a hostname or IP address your Django app will accept requests from.
Example parts:
"example.com"- allows requests from example.com"localhost"- allows requests from localhost"127.0.0.1"- allows requests from this IP".example.com"- allows all subdomains of example.com
python
ALLOWED_HOSTS = [
'example.com',
'localhost',
'127.0.0.1',
'.example.com',
]Example
This example shows a simple settings.py snippet where ALLOWED_HOSTS is set to allow local development and a production domain.
python
ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'mywebsite.com']
Output
When running the Django server, requests to 'localhost', '127.0.0.1', or 'mywebsite.com' will be accepted. Requests to other hosts will be blocked with a 400 Bad Request error.
Common Pitfalls
Common mistakes include:
- Leaving
ALLOWED_HOSTSempty in production, which causes Django to reject all requests. - Using
['*']in production, which disables host header validation and is insecure. - Forgetting to add your domain or IP, causing 400 errors.
Always specify exact hostnames or subdomains you expect.
python
# Wrong: ALLOWED_HOSTS = [] # Blocks all hosts in production # Wrong: ALLOWED_HOSTS = ['*'] # Insecure for production # Right: ALLOWED_HOSTS = ['mydomain.com', '.mydomain.com', 'localhost']
Quick Reference
| Setting | Description | Example |
|---|---|---|
| ALLOWED_HOSTS | List of allowed host/domain names | ['example.com', 'localhost', '127.0.0.1'] |
| Wildcard subdomains | Allow all subdomains of a domain | ['.example.com'] |
| Empty list | Blocks all hosts (not for production) | [] |
| Wildcard '*' | Allows all hosts (insecure) | ['*'] |
Key Takeaways
Always set ALLOWED_HOSTS in settings.py to your app's domain names or IPs.
Never leave ALLOWED_HOSTS empty or use ['*'] in production for security reasons.
Use a leading dot to allow all subdomains of a domain, e.g., '.example.com'.
If ALLOWED_HOSTS is misconfigured, Django returns a 400 Bad Request error.
Test your host settings locally and in production to avoid request blocking.