Django ALLOWED_HOSTS通过Apache接受本地IP

Zor*_*duk 7 apache django mod-wsgi

我正在为Apache提供Django应用程序.在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 = ['*']

Zor*_*duk 9

根据@rnevius的建议,并根据@AlvaroAV关于如何在django中设置自定义中间件的指南,我已经成功解决了这个中间件:

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
Run Code Online (Sandbox Code Playgroud)

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

多谢你们!:)