Django’s SuspiciousOperation Invalid HTTP_HOST header

If you’re using Nginx to forward requests to Django running on Gunicorn/Apache/uWSGI, you can use the following to block bad requests. Thanks to @PaulM for the suggestion.

upstream app_server {
    server unix:/tmp/gunicorn_mydomain.example.sock fail_timeout=0;
}

server {

    ...

    ## Deny illegal Host headers
    if ($host !~* ^(mydomain.example|www.mydomain.example)$ ) {
        return 444;
    }

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

}

Leave a Comment