What this thread does
The problem
What should you inspect when a request returns Bad Request (400) after setting DEBUG = False?
What the sources say
- Django's settings reference for 6.1 says failing to set
ALLOWED_HOSTSproperly withDEBUG=Falseresults in Bad Request (400). Entries are host/domain names; matching excludes the port. A leading dot such as.example.commatches the domain and its subdomains. If no entry matches,get_host()raisesSuspiciousOperation. - Django's deployment checklist says a suitable
ALLOWED_HOSTSis required with DEBUG off. The deployment checklist says that if you use a wildcard, you must validate the Host HTTP header yourself or otherwise ensure you are not vulnerable to these attacks. - The logging reference describes
django.security.DisallowedHostfor invalid Host headers. These security events are distinct from ordinary request logging. - The proxy setting should only be enabled if a proxy sets that header.
What to do (our recommendations)
1. Read the exact error in your configured security logging. For suspected host validation, inspect django.security.DisallowedHost rather than assuming an ordinary request log contains it. 2. Put the intended public bare host names into ALLOWED_HOSTS (for example the domain, plus localhost for local checks). A leading dot such as .example.com matches the domain and all subdomains. 3. Behind a proxy, make the proxy send the original Host header, and set USE_X_FORWARDED_HOST only if the proxy really sets that header (Django's docs say to enable it only then). 4. If the value comes from an environment variable, inspect the resulting ALLOWED_HOSTS at startup: confirm it contains the intended host names.
How to describe it to your agent (our recommendation)
My Django app returns 400 when DEBUG is False. Enable file logging, reproduce the request, and tell me the Host value in the log. Then fix ALLOWED_HOSTS with bare host names only. Do not use '*' in production and do not set DEBUG back to True.
Mistakes to check (our recommendations)
- Putting
https://example.comorexample.com:8000intoALLOWED_HOSTS. - Using
'*'as the permanent fix. - Leaving the debug log file on after the fix.
Limits
Our recommendation: investigate other causes if your security logging does not indicate a host-validation error.
Started from a post by @Martijn Pieters, Yuseferi, ki9 (Stack Overflow); Django docs, packaged by the editor. Original post