Django ALLOWED_HOSTS IPs range

不问归期 提交于 2020-02-17 06:00:27

问题


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

Something like this:

ALLOWED_HOSTS = ['172.17.*.*']

回答1:


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




回答2:


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.




回答3:


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




回答4:


Here is a quick and dirty solution.

ALLOWED_HOSTS += ['172.17.{}.{}'.format(i,j) for i in range(256) for j in range(256)]



回答5:


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



来源:https://stackoverflow.com/questions/37031749/django-allowed-hosts-ips-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!