Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django ALLOWED_HOSTS IPs range

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

Something like this:

ALLOWED_HOSTS = ['172.17.*.*']
like image 337
Alex T Avatar asked May 04 '16 15:05

Alex T


Video Answer


3 Answers

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.

like image 193
Alasdair Avatar answered Oct 21 '22 22:10

Alasdair


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()), ] 

Update. If you are using docker the following code is better as gethostbyname doesn't get the correct information.

from socket import gethostname, gethostbyname, gethostbyname_ex
ALLOWED_HOSTS = [ gethostname(), ] + list(set(gethostbyname_ex(gethostname())[2]))

The reason it gets converted to a set is that fact that gethostbyname_ex can return duplicates.

The link to the ticket on django website is.

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

like image 43
Thomas Turner Avatar answered Oct 21 '22 21:10

Thomas Turner


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

like image 26
alexmuller Avatar answered Oct 21 '22 23:10

alexmuller