Django ALLOWED_HOSTS to accept local IPs through Apache
Following the recommendation from @rnevius, and based on the guidelines from @AlvaroAV in how to setup custom middleware in django, I've managed to solve with this middleware:
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
and setting ALLOWED_HOSTS = ['*']
in settings.py
no longer opens up for all hosts in an uncontrolled way.
Thanks guys! :)
For those wondering what this should be in Django 2.0.dev (In line with @Zorgmorduk's answer)
You need to make the object callable: django middleware docs
- Create a folder named middleware in yourproject/yourapp/
- Create an empty file
__init__.py
inside yourproject/yourapp/middleware folder. - Create another file, in this case
filter_host_middleware.py
Add this code inside
filter_host_middleware.py
:from django.http import HttpResponseForbidden class FilterHostMiddleware(object): def __init__(self, process_request): self.process_request = process_request def __call__(self, request): response = self.process_request(request) return response def process_request(self, request):` # use the same process_request definition as in @Zorgmorduk's answer
- add yourapp.middleware.filter_host_middleware.FilterHostMiddleware to your MIDDLEWARE in yourproject's
settings.py
; additionally changeALLOWED_HOSTS=['*']
You are all set!