Django ALLOWED_HOSTS IPs range

前端 未结 5 1702
醉梦人生
醉梦人生 2021-01-31 08:46

Is there a way to set a range of ALLOWED_HOSTS IPs in django?

Something like this:

ALLOWED_HOSTS = [\'172.17.*.*\']
相关标签:
5条回答
  • 2021-01-31 09:28

    I posted a ticket on Django however I was shown this could be achieved by doing the following

    from socket import gethostname, gethostbyname 
    ALLOWED_HOSTS = [ gethostname(), gethostbyname(gethostname()), ] 
    

    https://code.djangoproject.com/ticket/27485

    0 讨论(0)
  • 2021-01-31 09:43

    Here is a quick and dirty solution.

    ALLOWED_HOSTS += ['172.17.{}.{}'.format(i,j) for i in range(256) for j in range(256)]
    
    0 讨论(0)
  • 2021-01-31 09:44

    I've found such solution for filtering range of IPs:

    https://stackoverflow.com/a/36222755/3766751

    Using this approach we can filter IPs by any means (f.e. with regex).

    from django.http import HttpResponseForbidden
    
    class FilterHostMiddleware(object):
    
        def process_request(self, request):
    
            allowed_hosts = ['127.0.0.1', 'localhost']  # specify complete host names here
            host = request.META.get('HTTP_HOST')
    
            if host[len(host)-10:] == 'dyndns.org':  # if the host ends with dyndns.org then add to the allowed hosts
                allowed_hosts.append(host)
            elif host[:7] == '192.168':  # if the host starts with 192.168 then add to the allowed hosts
                allowed_hosts.append(host)
    
            if host not in allowed_hosts:
                raise HttpResponseForbidden
    
            return None
    

    Thanks for @Zorgmorduk

    0 讨论(0)
  • 2021-01-31 09:45

    No, this is not currently possible. According to the docs, the following syntax is supported:

    ['www.example.com']  # Fully qualified domain
    ['.example.com']  # Subdomain wildcard, matches example.com and www.example.com 
    ['*']  # Matches anything
    

    If you look at the implementation of the validate_host method, you can see that using '*' by itself is allowed, but using * as a wildcard as part of a string (e.g. '172.17.*.*') is not supported.

    0 讨论(0)
  • 2021-01-31 09:45

    Mozilla have released a Python package called django-allow-cidr which is designed to solve exactly this problem.

    The announcement blog post explains that it's useful for things like health checks that don't have a Host header and just use an IP address.

    You would have to change your IP address '172.17.*.*' slightly to be a CIDR range like 172.17.0.0/16

    0 讨论(0)
提交回复
热议问题