How to disable Django's invalid HTTP_HOST error?

DjangoLoggingHttp Host

Django Problem Overview


Ever since I deployed a site running Django 1.7 alpha (checked out from Git), I've been occasionally receiving error messages with titles like:

> "Invalid HTTP_HOST header: 'xxx.xxx.com'"

I realize that this is due to the Host: HTTP header being set to a hostname not listed in ALLOWED_HOSTS. However, I have no control over when and how often someone sends a request to the server with a forged hostname. Therefore I do not need a bunch of error emails letting me know that someone else is attempting to do something fishy.

Is there any way to disable this error message? The logging settings for the project look like this:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

Django Solutions


Solution 1 - Django

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

Solution 2 - Django

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.

Solution 3 - Django

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

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    listen 443 ssl default_server;
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
    return 444;
}


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

Solution 4 - Django

Using Apache 2.4, there's no need to use mod_setenvif. The HTTP_HOST is already a variable and can be evaluated directly:

WSGIScriptAlias / /path/to/wsgi.py

<Directory /path/to>
    <Files wsgi.py>
        Require expr %{HTTP_HOST} == "example.com"
    </Files>
</Directory>

Solution 5 - Django

you could silence that particular SuspiciousOperation with something like

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

see this for more reference https://docs.djangoproject.com/en/dev/topics/logging/#django-security

EDIT

you also need to add a 'null' handler:

'handlers': {
    'null': {
        'level': 'DEBUG',
        'class': 'logging.NullHandler',
    },
}

probably you only need to add this and modify the level of error (replacing DEBUG with 'ERROR').

as always refer to the the documentation for the complete syntax and semantic.

Solution 6 - Django

Another way to block requests with an invalid Host header before it reaches Django is to use a default Apache config with a <VirtualHost> that does nothing but return a 404.

<VirtualHost *:80>
</VirtualHost>

If you define this as your first virtual host (e.g. in 000-default.conf) and then follow it with your 'real' <VirtualHost>, complete with a <ServerName> and any <ServerAlias> entries that you want to match, Apache will return a 404 for any requests with a Host header that does not match <ServerName> or one of your <ServerAlias> entries. The key it to make sure that the default, 404 <VirtualHost> is defined first, either by filename ('000') or the first entry in your config file.

I like this better than the popular solution above because it is very explicit and easy to extend.

Solution 7 - Django

The django docs address this specifically. They recommend putting this in your logging settings

LOGGING = {
    # ...
    "handlers": {
        # ...
        "null": {
            "class": "logging.NullHandler",
        },
    },
    "loggers": {
        # ...
        "django.security.DisallowedHost": {
            "handlers": ["null"],
            "propagate": False,
        },
    },
}

Additionally, if you are using Sentry, you need to add this to prevent Sentry from picking it up:

from sentry_sdk.integrations.logging import ignore_logger
ignore_logger("django.security.DisallowedHost")

Solution 8 - Django

I can't comment yet, but since Order Deny, Allow is deprecated, the way to do this in a virtual host with the current Require directive is:

<Directory /var/www/html/>
    SetEnvIfNoCase Host example\.com VALID_HOST
    Require env VALID_HOST
    Options
</Directory>

Solution 9 - Django

The other answers on this page are correct if you're simply looking to hide or disable the warning. If you're intentionally allowing every hostname the special value of * can be used as the ALLOWED_HOSTS setting.

Note: This may introduce security vulnerabilities.

> Django uses the Host header provided by the client to construct URLs in certain cases. While these values are sanitized to prevent Cross Site Scripting attacks, a fake Host value can be used for Cross-Site Request Forgery, cache poisoning attacks, and poisoning links in emails. > > Because even seemingly-secure web server configurations are susceptible to fake Host headers, Django validates Host headers against the ALLOWED_HOSTS setting in the django.http.HttpRequest.get_host() method.

To prevent hostname checking entirely, add the following line to your settings.py:

ALLOWED_HOSTS = ['*']

Source: https://github.com/django/django/blob/33c365781abbcc1b21a31b31d95d344a174df0d5/django/http/request.py#L653-L668

def validate_host(host, allowed_hosts):
    """
    Validate the given host for this site.

    Check that the host looks valid and matches a host or host pattern in the
    given list of ``allowed_hosts``. Any pattern beginning with a period
    matches a domain and all its subdomains (e.g. ``.example.com`` matches
    ``example.com`` and any subdomain), ``*`` matches anything, and anything
    else must match exactly.

    Note: This function assumes that the given host is lowercased and has
    already had the port, if any, stripped off.

    Return ``True`` for a valid host, ``False`` otherwise.
    """
    return any(pattern == '*' or is_same_domain(host, pattern) for pattern in allowed_hosts)

Solution 10 - Django

for multiple valid hosts you can:

SetEnvIfNoCase Host example\.com VALID_HOST
SetEnvIfNoCase Host example2\.com VALID_HOST
SetEnvIfNoCase Host example3\.com VALID_HOST
Require env VALID_HOST

Solution 11 - Django

In setting.py set:

ALLOWED_HOSTS = ['yourweb.com']

Solution 12 - Django

Here's NGINX block needed to prevent your django from receiving such requests.

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    listen 443 ssl default_server;
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
    return 444;
}

Solution 13 - Django

Also to handle the below error through Apache:

  • Invalid HTTP_HOST header: '_my.domain.com'. The domain name provided is not valid according to RFC 1034/1035.

We can use regex, ^[^_]+ would match a string of 1 or more character containing any character except underscore in the subdomain as in the below case.

We can apply it to wsgi.py file

<VirtualHost xxx.xxx.xxx.xxx:XX>
    ...

    SetEnvIfNoCase Host "^[^_]+\.my-domain\.com" VALID_HOST
    <Files wsgi.py>
        <RequireAll>
            Require all granted
            Require env VALID_HOST
        </RequireAll>
    </Files>
    
    ...
</VirtualHost>

With Require expr:

<VirtualHost xxx.xxx.xxx.xxx:XX>
    ...


    <Files wsgi.py>

        Require expr %{HTTP_HOST} =~ m#^[^_]+\.my-domain\.com#

    </Files>


    ...

</VirtualHost>

Or we can use <Location "/">, which is an easy way to apply a configuration to the entire server.

<VirtualHost xxx.xxx.xxx.xxx:XX>
    ...

    SetEnvIfNoCase Host "^[^_]+\.my-domain\.com" VALID_HOST
    <Location />
        <RequireAll>
            Require all granted
            Require env VALID_HOST
        </RequireAll>
    </Location>
    
    ...
</VirtualHost>

From Apache docs:

> When to use <Location "/"> > > Use <Location> to apply directives to content that lives outside the > filesystem. For content that lives in the filesystem, use > and . An exception is <Location "/">, which is an easy way to > apply a configuration to the entire server.

The answer is based on Apache Module mod_setenvif and how to block persistent requests from a particular robot.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNathan OsmanView Question on Stackoverflow
Solution 1 - DjangoMark LavinView Answer on Stackoverflow
Solution 2 - DjangoVinay SajipView Answer on Stackoverflow
Solution 3 - DjangoJanusz SkoniecznyView Answer on Stackoverflow
Solution 4 - DjangoliquidkiView Answer on Stackoverflow
Solution 5 - DjangoDRCView Answer on Stackoverflow
Solution 6 - DjangoBob BarcklayView Answer on Stackoverflow
Solution 7 - DjangoZagsView Answer on Stackoverflow
Solution 8 - Djangof71316View Answer on Stackoverflow
Solution 9 - DjangoWolphView Answer on Stackoverflow
Solution 10 - DjangoashierView Answer on Stackoverflow
Solution 11 - DjangoMu Sian GongView Answer on Stackoverflow
Solution 12 - DjangodiscoverView Answer on Stackoverflow
Solution 13 - DjangoNKSMView Answer on Stackoverflow