Is there a way to set a range of ALLOWED_HOSTS IPs in django?
Something like this:
ALLOWED_HOSTS = ['172.17.*.*']
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With