Configuring ALLOWED_HOSTS for Django Production Deployment
When setting DEBUG = False in Django's settings file, attempting to run the development server will result in an error.
python manage.py runserver 8888
CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False.
This error indicates that the ALLOWED_HOSTS configuration is mandatory when debug mode is disabled for security reasons.
Setting ALLOWED_HOSTS
The ALLOWED_HOSTS setting accepts a list of strings representing valid host/domain names for the application. This prevents HTTP Host header attacks.
To allow a specific domain and its subdomains:
ALLOWED_HOSTS = [
'.mydomain.com', # Matches mydomain.com and any subdomain
]
For development or testing environments where you need to accept all hosts, you can use a wildcard:
ALLOWED_HOSTS = ['*']
Warning: Using '*' makes your application accept any host header. Ensure proper host validation is implemented elsewhere in production, such as at the web server layer.
After configuring ALLOWED_HOSTS, the development server will start normally.
Security Context
According to Django's documentation, ALLOWED_HOSTS provides protection against cache poisoning and malicious links in emails by validating the Host header. When DEBUG = True or during tesst execution, this validation is disabled.
In Django 1.7+, trailing dots in hostnames are automatically handled, so entries like '.example.com.' are no longer necessary. Host validtaion occurs through request.get_host(). Direct access to request.META['HTTP_HOST'] bypasses this security check.
For detailed specifications, refer to the official Django documentation on settings.