Gabriel Saldaña's blog

personal blog, photography and programming

Avoid Django’s invalid HTTP_HOST error message

Invalid HTTP_HOST error log

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

}

About the author

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

Posted Under
Tagged

Post navigation

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: