Django 'DisallowedHost: Invalid HTTP_HOST Header': Fix
Your live Django site returns 400 Bad Request with 'Invalid HTTP_HOST header'? Read the host in the message, fix ALLOWED_HOSTS, and stop settings from being overwritten or the proxy from sending the wrong Host.
"DisallowedHost: Invalid HTTP_HOST header: 'x'. You may need to add 'x' to ALLOWED_HOSTS" means the Host header of the request is not in the ALLOWED_HOSTS list that Django actually loaded. Copy the host from the error message exactly, without the port, add it to ALLOWED_HOSTS, restart the app, and check that no later line in your settings overwrites the list.
With DEBUG = True, Django quietly allows localhost and 127.0.0.1, so nothing fails on your laptop. With DEBUG = False, every other host is rejected with a 400. That is why the error shows up on the first production deploy, or after you move to a new domain, server or platform. Here is how to find the cause in order.
Step 1: Read the Host in the Error
Django prints the rejected value. It is the fastest clue you have:
django.core.exceptions.DisallowedHost: Invalid HTTP_HOST header: 'myapp.onrender.com'. You may need to add 'myapp.onrender.com' to ALLOWED_HOSTS.
Look at three things:
- The name. Is it your domain, a platform subdomain such as
*.onrender.com, a raw IP address, or something strange like1.2.3.4:8000? - A port. Do not include the port in
ALLOWED_HOSTS.example.com:8080becomesexample.com. - Who sent it. If the host is your own domain or your load balancer's health check, fix the setting. If it is a random IP or a domain you never owned, it is a scanner and you can ignore it (see Step 6).
Reports on Render, DigitalOcean and Fly.io all start with the platform host missing from the list.
Step 2: Add the Host to ALLOWED_HOSTS
# settings.py
ALLOWED_HOSTS = [
"example.com",
"www.example.com",
"myapp.onrender.com", # platform URL, if you still use it
]
Rules that trip people up:
- Entries are plain host names. No
https://, no path, no port. - A leading dot matches the domain and all its subdomains:
".example.com"coversexample.comandapi.example.com. - Every entry must be a separate string. A missing comma makes Python join two strings into one bad entry. A Django forum thread shows
'3.15.27.43,' 'localhost'turning into one value. - Add the
wwwversion and any staging domain you serve from the same app.
Avoid ALLOWED_HOSTS = ["*"] as a permanent fix. It turns off the Host header check that protects against host header attacks, for example poisoned password reset links.
Step 3: Check That the Setting Is Really Loaded
This is the most common reason the error stays after you "already fixed it". One forum post and an AWS question describe the same shape: the right value is in the file, but Django does not use it.
Print what the running process sees:
python manage.py shell -c "from django.conf import settings; print(settings.DEBUG, settings.ALLOWED_HOSTS)"
Run this on the server, with the same environment variables as the app. If the output is not what you expect, look for:
- A later line that overwrites the list. A block for production sets the hosts, then
ALLOWED_HOSTS = ["localhost", "127.0.0.1"]appears further down. - The wrong settings module.
DJANGO_SETTINGS_MODULEpoints tosettings.devon the server, ormanage.pyandwsgi.pyuse different modules. - A missing environment variable. The list comes from
os.environ.get("ALLOWED_HOSTS", ""), the variable is not set on the server, and the result is an empty list or['']. - A bad split.
"a.com, b.com".split(",")gives' b.com'with a leading space. Use.strip().
A safe way to read hosts from the environment:
import os
ALLOWED_HOSTS = [
h.strip()
for h in os.environ.get("DJANGO_ALLOWED_HOSTS", "").split(",")
if h.strip()
]
Then set DJANGO_ALLOWED_HOSTS=example.com,www.example.com in your hosting dashboard or .env file.
Step 4: Restart the App
Django reads settings once at start. After you change the file or the variable, restart the process:
sudo systemctl restart gunicorn
On a platform, trigger a redeploy. A changed environment variable usually needs one too. If you run several workers or containers, make sure all of them restarted, otherwise some requests pass and some fail, which looks random.
Step 5: Check What the Proxy Sends as Host
If the rejected host is 127.0.0.1:8000, localhost or an internal name like django, the proxy is passing its own upstream address instead of the one the user typed. Fix the proxy, not the list.
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
}
Without proxy_set_header Host $host;, nginx sends the name from proxy_pass. A Django forum thread on nginx and gunicorn covers this setup. If the proxy sets X-Forwarded-Host instead, you also need USE_X_FORWARDED_HOST = True, and you should only turn that on when the proxy always overwrites the header.
The same proxy headers matter for CSRF. If login forms also fail with a 403, read Django CSRF Verification Failed in Production.
Step 6: Health Checks and Scanner Noise
Two cases cause a steady trickle of this error even when the site works:
- Load balancer health checks. They often call the instance by IP, for example
10.0.3.17. Django rejects it with a 400 and the balancer marks the instance unhealthy. Fix: answer the health check before Django's host check, in nginx or the load balancer, or add the instance IP if it is stable. Do not use*just for this. - Bots. Public servers get requests with random
Hostvalues from scanners. Django returns 400 and logs an error each time, which can flood your error tracker. Django logs these under thedjango.security.DisallowedHostlogger, so you can silence that one logger without hiding real errors:
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"loggers": {
"django.security.DisallowedHost": {"handlers": ["null"], "propagate": False},
},
"handlers": {"null": {"class": "logging.NullHandler"}},
}
Only do this once you have confirmed that the rejected hosts are noise.
Step 7: Catch It Before Users Do
A wrong ALLOWED_HOSTS fails every request, but only for the host that is missing. The common trap is adding a new domain or moving behind a CDN, where the main URL works and the new one returns 400 for everyone. If you want a wider view of slow gunicorn requests next, see Gunicorn WORKER TIMEOUT and 502 on Django.
How Relia Helps
Relia has a Python package that reports unhandled Django errors with the stack trace and the request that caused them. After a deploy it shows you which requests started failing and groups them into one incident in plain words, so a new 400 spike on one host stands out right after the release. Uptime monitors and checks of key pages also test your real domain from outside, which catches a domain that returns 400 while your main URL is fine. You can look around the live demo first.
FAQ
Can I use ALLOWED_HOSTS = ['*'] in production?
It removes the host check, so Django will accept any Host header. That weakens protection against host header attacks. Use it only as a short test to confirm the cause, then list real hosts.
Why does it work with DEBUG = True but not with DEBUG = False?
With DEBUG = True and an empty list, Django allows localhost, 127.0.0.1 and [::1]. With DEBUG = False it enforces the list strictly.
Do I add the port to ALLOWED_HOSTS?
No. Add only the host name. localhost:8000 is checked as localhost.
How do I allow all subdomains?
Use a leading dot, for example ".example.com". It matches example.com and every subdomain.
I added the host and it still fails. What now?
Print settings.ALLOWED_HOSTS from the running environment (Step 3), then restart every worker. Most of the time a later line, a wrong settings module or a missing environment variable is the cause.