Django ALLOWED_HOSTS IPs range

2020-05-18 10:13发布

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

Something like this:

ALLOWED_HOSTS = ['172.17.*.*']

5条回答
Explosion°爆炸
2楼-- · 2020-05-18 10:44

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

查看更多
爷的心禁止访问
3楼-- · 2020-05-18 10:48

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

查看更多
够拽才男人
4楼-- · 2020-05-18 10:48

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 * as a wildcard is not supported.

查看更多
时光不老,我们不散
5楼-- · 2020-05-18 10:48

Here is a quick and dirty solution.

ALLOWED_HOSTS += ['172.17.{}.{}'.format(i,j) for i in range(256) for j in range(256)]
查看更多
\"骚年 ilove
6楼-- · 2020-05-18 10:48

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

查看更多
登录 后发表回答