You can get the error “Invalid HTTP_HOST header” if you have the setting “ALLOWED_HOSTS” improperly configured. But what if it is properly configured and you keep getting this error for HTTP_HOSTs that are clearly messed up. Some bot or hacker is probably probing your site. All the more reason not to open up ALLOWED_HOSTS. What to do?
First you need to be able to create the error so you can be sure your fix worked. Here is how to do that:
curl -H "Host: sfdfsdff" https://your_website.com
If this command is doing what it should, you should get an HTTP 400. Then a little later the email.
Now that you can trigger the error at will, it’s time to stop it. There are many options discussed here. I like option of handling it in Nginx, like this:
upstream app_server {
server unix:/tmp/gunicorn_mydomain.com.sock fail_timeout=0;
}
server {
...
## Deny illegal Host headers
if ($host !~ ^(mydomain.com|www.mydomain.com)$ ) {
return 444;
}
}
When you are done, restart nginx:
service nginx restart
If it works correctly, curl should return: Empty reply from server
One thought on “Django Error: Invalid HTTP_HOST header”