django ALLOWED_HOSTS无法正常工作


问题内容

我的settings.py文件包含:

DEBUG = False
ALLOWED_HOSTS = [u'mydomainxxx.com']

但是,我能够发出如下所示的curl请求:curl -X GET https://mydomainxxx.com/api/ -H 'Authorization: Token some token'并获得响应。

我希望使用ALLOWED_HOSTS可以防止curl等命令从我的API获得响应。这是正常现象吗?


问题答案:

仅对于想要过滤引荐来源网址而不是IP地址的任何人,我们可以使用以下中间件:

from django.conf import settings
from django import http

class AllowHostsMiddleware(object):

    def process_request(self, request):
        referer_url = request.META.get('HTTP_REFERER','')
        if referer_url.startswith(settings.ALLOWED_REFERER_URL):
            return None
        return http.HttpResponseForbidden('<h1>Forbidden</h1>')