简体   繁体   English

django ALLOWED_HOSTS 不工作

[英]django ALLOWED_HOSTS not working

My settings.py file contains:我的 settings.py 文件包含:

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

Howevever, I'm able to fire a curl request like this: curl -X GET https://mydomainxxx.com/api/ -H 'Authorization: Token some token' and am getting the response.但是,我能够像这样发出 curl 请求: curl -X GET https://mydomainxxx.com/api/ -H 'Authorization: Token some token'并得到响应。

I was hoping that using ALLOWED_HOSTS will prevent commands like curl to get response from my API. Is this a normal behaviour?我希望使用ALLOWED_HOSTS会阻止像 curl 这样的命令从我的 API 获得响应。这是正常行为吗?

You are confusing the ALLOWED_HOSTS setting with something else. 您将ALLOWED_HOSTS设置与其他内容混淆。 It denotes the hostnames that your server will listen to; 它表示服务器将侦听的主机名; not the hostnames of connecting hosts. 不是连接主机的主机名。 There is no built in method to prevent it but you can easily write a middleware to check connecting hostnames. 没有内置的方法来阻止它,但您可以轻松编写中间件来检查连接主机名。

Your current setting will prevent this from getting a response: 您当前的设置将阻止此响应:

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

even if both mydomainxxx.com and another_domainxxx.com will resolve to the same IP Address. 即使mydomainxxx.comanother_domainxxx.com都将解析为相同的IP地址。

Just for anyone who would like to filter on referer url and not on ip address, we can use the following middleware: 对于想要过滤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>')

Add your domain or ip to the Allowed_Hosts and then type the following command将您的域或 ip 添加到Allowed_Hosts ,然后键入以下命令

sudo systemctl restart nginx

then然后

sudo systemctl restart gunicorn and

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM