Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django ALLOWED_HOSTS to accept local IPs through Apache

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 = ['*']?

like image 590
Zorgmorduk Avatar asked Mar 25 '16 12:03

Zorgmorduk


2 Answers

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! :)

like image 94
Zorgmorduk Avatar answered Nov 16 '22 02:11

Zorgmorduk


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

  1. Create a folder named middleware in yourproject/yourapp/
  2. Create an empty file __init__.py inside yourproject/yourapp/middleware folder.
  3. Create another file, in this case filter_host_middleware.py
  4. 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
    
  5. add yourapp.middleware.filter_host_middleware.FilterHostMiddleware to your MIDDLEWARE in yourproject's settings.py; additionally change ALLOWED_HOSTS=['*']

You are all set!

like image 41
Rishi Alluri Avatar answered Nov 16 '22 04:11

Rishi Alluri