问题
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 = ['*']
?
回答1:
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! :)
回答2:
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!
来源:https://stackoverflow.com/questions/36220260/django-allowed-hosts-to-accept-local-ips-through-apache