【问题标题】:django ALLOWED_HOSTS not workingdjango ALLOWED_HOSTS 不工作
【发布时间】:2016-06-06 15:24:27
【问题描述】:

我的 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 获得响应。 这是正常现象吗?

【问题讨论】:

  • 你打开调试了吗?
  • 如上所说,为假

标签: python django apache


【解决方案1】:

您将ALLOWED_HOSTS 设置与其他设置混淆了。它表示您的服务器将侦听的主机名;不是连接主机的主机名。没有内置方法来防止它,但您可以轻松编写一个中间件来检查连接的主机名。

您当前的设置将阻止此响应:

curl -X GET http://another_domainxxx.com/api/ -H 'Authorization: Token some token' 

即使 mydomainxxx.comanother_domainxxx.com 都将解析为相同的 IP 地址。

【讨论】:

  • 感谢 Selcuk,您能否指出我可以编写此中间件的好资源?
  • @SaurabhVerma 如果你想通过IP地址进行限制,可以试试github.com/muccg/django-iprestrict或者修改为根据主机名进行限制。
  • 谢谢,我也添加了我的答案,这对我有用。
【解决方案2】:

对于任何想要过滤referer url而不是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>')

【讨论】:

    【解决方案3】:

    将您的域或 ip 添加到 Allowed_Hosts 然后输入以下命令

    sudo systemctl restart nginx
    

    然后

    sudo systemctl restart gunicorn and
    

    【讨论】:

      猜你喜欢
      • 2018-07-28
      • 1970-01-01
      • 1970-01-01
      • 2016-08-30
      • 2018-04-24
      • 2018-02-17
      • 2016-06-21
      • 2015-02-27
      • 2017-01-20
      相关资源
      最近更新 更多