I'm serving a Django app with Apache.
In Django's settings.py I have DEBUG = False, therefore I had to allow some hosts, like: ALLOWED_HOSTS = ['.dyndns.org', 'localhost']. This works fine, however I would like to have the server accessible on the local network via its internal IP address as well, like: 192.168.0.x, or 127.0.0.1, etc. How could I define 192.* or 127.* in ALLOWED_HOSTS, if I'd like to avoid opening up the access entirely by ALLOWED_HOSTS = ['*']?
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
__init__.py inside yourproject/yourapp/middleware folder.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
settings.py; additionally change ALLOWED_HOSTS=['*']
You are all set!
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