Django ALLOWED_HOSTS通过Apache接受本地IP [英] Django ALLOWED_HOSTS to accept local IPs through Apache
问题描述
在Django的settings.py中,我有
DEBUG = False
,因此我不得不允许一些主机,如: ALLOWED_HOSTS = ['.dyndns .org','localhost']
。这样做很好,但是我想通过其内部IP地址在本地网络上访问服务器,如: 192.168.0.x
或 127.0.0.1
等等。我如何定义 192。*
或 127。*
ALLOWED_HOSTS ,如果我想避免通过 ALLOWED_HOSTS = ['*'] $ c $完全访问c>?解决方案根据@rnevius的建议,并根据@AlvaroAV在如何在django中设置自定义中间件,我已经设法解决这个中间件:
从django.http导入H pre $ p
class FilterHostMiddleware(object)
def process_request(self,request):
allowed_hosts = ['127.0.0.1','localhost']#在此指定完整的主机名
ho st = request.META.get('HTTP_HOST')
如果主机[len(主机)-10:] =='dyndns.org':#如果主机以dyndns.org结尾然后添加允许的主机
allowed_hosts.append(host)
elif host [:7] =='192.168':#如果主机从192.168开始,然后添加到允许的主机
allowed_hosts.append (主机)
如果主机不在allowed_hosts中:
raise HttpResponseForbidden
返回无
并在 settings.py
ALLOWED_HOSTS = ['*'] >不再以不受控制的方式打开所有主机。
谢谢你们! :)
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! :)
这篇关于Django ALLOWED_HOSTS通过Apache接受本地IP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!