How to disable Django's invalid HTTP_HOST error?

前端 未结 11 911
日久生厌
日久生厌 2020-12-04 10:12

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:

\"Inv

相关标签:
11条回答
  • 2020-12-04 11:06

    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.

    0 讨论(0)
  • 2020-12-04 11:07

    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;
        ...
    
    0 讨论(0)
  • 2020-12-04 11:07

    In setting.py set:

    ALLOWED_HOSTS = ['yourweb.com']
    
    0 讨论(0)
  • 2020-12-04 11:08

    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>
    
    0 讨论(0)
  • 2020-12-04 11:14

    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,
            },
        },
    }
    
    0 讨论(0)
提交回复
热议问题