How to disable Django's invalid HTTP_HOST error?

You shouldn't be ignoring this error. Instead you should be denying the request before it reaches your Django backend. To deny requests with no HOST set you can use

SetEnvIfNoCase Host .+ VALID_HOST
Order Deny,Allow
Deny from All
Allow from env=VALID_HOST

or force the match to a particular domain (example.com)

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

You can add this to the loggers section of your logging configuration:

    'django.security.DisallowedHost': {
        'handlers': ['mail_admins'],
        'level': 'CRITICAL',
        'propagate': False,
    },

This sets the logging threshold to above the ERROR level that Django uses when a SuspiciousOperation is detected.

Alternatively, you can use e.g. a FileHandler to log these events without emailing them to you. For example, to use a dedicated file just for these specific events, you could add this to the handlers section:

    'spoof_logfile': {
        'level': 'ERROR',
        'class': 'logging.FileHandler',
        'filename': '/path/to/spoofed_requests.log',
    },

and then use this in the loggers section:

    'django.security.DisallowedHost': {
        'handlers': ['spoof_logfile'],
        'level': 'ERROR',
        'propagate': False,
    },

Note that the suggestion made in the Django docs, to use

    'django.security.DisallowedHost': {
        'handlers': ['null'],
        'propagate': False,
    },

depends on you running Python 2.7 or later - on 2.6, logging doesn't have a NullHandler.


Here's NGINX example that should prevent your django from receiving rubbish requests.

server {
    listen 80 default_server;
    server_name _;
    return 418;
}


server {
    listen 80;
    # This will keep Django from receiving request with invalid host
    server_name <SERVER_IP> your.domain.com;
    ...