0
0
DjangoDebug / FixBeginner · 3 min read

How to Fix Disallowed Host Error in Django Quickly

The Django DisallowedHost error happens when a request comes from a host not listed in ALLOWED_HOSTS in your settings.py. To fix it, add the domain or IP address you expect to receive requests from into the ALLOWED_HOSTS list.
🔍

Why This Happens

Django protects your app from HTTP Host header attacks by checking if the incoming request's host is in the ALLOWED_HOSTS list. If the host is missing or incorrect, Django raises a DisallowedHost error.

python
ALLOWED_HOSTS = []
Output
django.core.exceptions.DisallowedHost: Invalid HTTP_HOST header: 'example.com'. You may need to add 'example.com' to ALLOWED_HOSTS.
🔧

The Fix

Update your ALLOWED_HOSTS in settings.py to include the domain names or IP addresses your app will serve. This tells Django to accept requests from these hosts.

python
ALLOWED_HOSTS = ['example.com', 'www.example.com', 'localhost', '127.0.0.1']
Output
No error; Django accepts requests from the specified hosts.
🛡️

Prevention

Always set ALLOWED_HOSTS before deploying your Django app to production. Use environment variables or configuration files to manage hosts safely. Avoid using ['*'] in production as it disables this security check.

Test your app locally with localhost and your production domain to ensure hosts are correctly configured.

⚠️

Related Errors

Other common errors include:

  • ImproperlyConfigured: Happens if ALLOWED_HOSTS is empty in production.
  • CSRF verification failed: Can occur if host headers don't match expected values.

Fix these by ensuring your host and CSRF settings align with your deployment environment.

Key Takeaways

Add all expected domain names and IPs to ALLOWED_HOSTS in settings.py.
Never leave ALLOWED_HOSTS empty in production to avoid security errors.
Use environment variables to manage ALLOWED_HOSTS for flexibility.
Avoid using ALLOWED_HOSTS = ['*'] in production as it disables host validation.
Test your app with all hostnames you expect to serve before deployment.