Categories
Programming & Web Development

Avoid Django’s invalid HTTP_HOST error message

Invalid HTTP_HOST error log

I have several Django projects published, and I constantly get my email inbox and log files inundated with errors of spiders and hack attempts to connect to my applications. Those error messages have the email subject: “[Django] ERROR (EXTERNAL IP): Invalid HTTP_HOST …”.

This is due to a Django’s security setting ALLOWED_HOSTS to prevent attacks. Better explained by Django’s documentation page:

This is a security measure to prevent an attacker from poisoning caches and triggering password reset emails with links to malicious hosts by submitting requests with a fake HTTP Host header, which is possible even under many seemingly-safe web server configurations.

At first, I thought of trying to configure Django’s logging to ignore those errors, but I knew that was not the right way to fix the situation. After several attempts, I found the right solution to the problem: a way to configure the web server to stop those connection attempts before they reach Django.

Here’s a configuration example for Apache web server (taken from StackOverflow):

SetEnvIfNoCase Host example\.com VALID_HOST
Order Deny,Allow
Deny from All
Allow from env=VALID_HOST

Here’s a configuration example for Nginx web server (more details here):

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;
    }

    location  / {
        proxy_pass               http://app_server;
        ...
    }

}

By Gabriel Saldaña

Gabriel Saldaña is a web developer, photographer and free software advocate. Connect with him on and Twitter

2 replies on “Avoid Django’s invalid HTTP_HOST error message”

Thank you for your post, it really helped me, I would like to add for the Django MOD-WSGI users of us here is how I implemented the solution:
WSGIScriptAlias / /path/to/wsgi.py

Require expr %{HTTP_HOST} in {“example.com”, “www.example.com”}

Oh, that didn’t come out right at all lol,
That require expression should be nested in the “Files wsgi.py” tag that is nested in the “Directory path-to-wsgy” tag. Hope that makes sense

Comments are closed.