Django的ALLOWED_HOSTS接受通过Apache的本地IP地址 [英] Django ALLOWED_HOSTS to accept local IPs through Apache

查看:1314
本文介绍了Django的ALLOWED_HOSTS接受通过Apache的本地IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我服与Apache一个Django应用程序。
在Django的settings.py我有 DEBUG =假,所以我不得不让一些主机,如: ALLOWED_HOSTS = ['.dyndns.org', 'localhost'的] 。这工作得很好,但是我想有通过其内部的IP地址在本地网络上访问服务器,以及像: 192.168.0.X 127.0.0.1 ,等我怎么可以定义 192。* 127。* ALLOWED_HOSTS ,如果我想用 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 = ['*']?

推荐答案

继@rnevius的建议,并根据从@AlvaroAV中的如何设置自定义的中间件在Django ,我已经成功与该中间件解决:

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

settings.py 设置 ALLOWED_HOSTS = ['*'] 不再开辟了在所有主机不受控制的方式。

and setting ALLOWED_HOSTS = ['*'] in settings.py no longer opens up for all hosts in an uncontrolled way.

谢谢你们! :)

这篇关于Django的ALLOWED_HOSTS接受通过Apache的本地IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆