A Django middleware that allows you to specify a list of allowed hosts using CIDR notation.
Install using pip:
pip install django-cidr-allowed-hosts
Add the middleware at the top of your MIDDLEWARE
settings:
MIDDLEWARE = [
'cidr.middleware.CIDRMiddleware',
...
]
Add the CIDR_ALLOWED_HOSTS
setting to your settings:
CIDR_ALLOWED_HOSTS = ["0.0.0.0/0"] # allows any IPv4
And that should be it.
ALLOWED_HOSTS
will still work as expected. Since the middleware overrides theALLOWED_HOSTS
setting to"*"
, the value provided originally toALLOWED_HOSTS
will be stored inORIGINAL_ALLOWED_HOSTS
and used to check if the request should be allowed.- If
CIDR_ALLOWED_HOSTS
is not set, the middleware will not be used. - If
ALLOWED_HOSTS
contains"*"
andCIDR_ALLOWED_HOSTS
is set, the middleware will raiseMiddlewareNotUsed
exception. CIDR_ALLOWED_HOSTS
must follow the CIDR notation.- Only IPv4 is supported.
python3 -m virtualenv venv source venv/bin/activate pip3 install tox tox
This project was inspired by django-allow-cidr