How to disable Django's invalid HTTP_HOST error?

前端 未结 11 917
日久生厌
日久生厌 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 10:57

    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)
    

提交回复
热议问题