django配置(setting)之ALLOWED_HOSTS

django配置(setting)之ALLOWED_HOSTS

django官方文档解释:

ALLOWED_HOSTS¶
Default: [] (Empty list)

A list of strings representing the host/domain names that this Django site can serve. This is a security measure to prevent HTTP Host header attacks, which are possible even under many seemingly-safe web server configurations.

Values in this list can be fully qualified names (e.g. 'www.example.com'), in which case they will be matched against the request’s Host header exactly (case-insensitive, not including port). A value beginning with a period can be used as a subdomain wildcard: '.example.com' will match example.com, www.example.com, and any other subdomain of example.com. A value of '*' will match anything; in this case you are responsible to provide your own validation of the Host header (perhaps in a middleware; if so this middleware must be listed first in MIDDLEWARE).

Django also allows the fully qualified domain name (FQDN) of any entries. Some browsers include a trailing dot in the Host header which Django strips when performing host validation.

If the Host header (or X-Forwarded-Host if USE_X_FORWARDED_HOST is enabled) does not match any value in this list, the django.http.HttpRequest.get_host() method will raise SuspiciousOperation.

When DEBUG is True and ALLOWED_HOSTS is empty, the host is validated against ['localhost', '127.0.0.1', '[::1]'].

This validation only applies via get_host(); if your code accesses the Host header directly from request.META you are bypassing this security protection.

Changed in Django 1.10.3:
In older versions, ALLOWED_HOSTS wasn’t checked if DEBUG=True. This was also changed in Django 1.9.11 and 1.8.16 to prevent a DNS rebinding attack.

理解AllOWED_HOSTS

settings.py

  • ALLOWED_HOSTS是配置在Django项目中的settings.py文件中的,Django设置文件包含Django安装的所有配置。

注意: settings.py设置文件只是一个带有模块级别变量的Python模块。

  • 由于settings.py设置文件时Python模块,因此以下内容适用:
    • 它不允许Python语法错误。
    • 它可以使用普通的Python语法动态分配设置。例如: MY_SETTING = [str(i) for i in range(30)]
    • 它可以从其他设置文件导入值。

ALLOWED_HOSTS的作用

  • ALLOWED_HOSTS是为了限定请求中的host值,以防止黑客构造包来发送请求。只有在列表中的host才能访问。

注意:在这里本人强烈建议不要使用*通配符去配置,另外当DEBUG设置为False的时候必须配置这个配置。否则会抛出异常。

ALLOWED_HOSTS的配置中文说明

  • ALLOWED_HOSTS后面所跟的属性值是一个字符串列表值,这个字符串列表值表示当下这个Django站点可以提供的host/domain(主机/域名)。这是一种安全措施,通过使用伪造的HTTP主机标头提交请求来防止攻击者中毒缓存并触发带有恶意主机链接的密码重置电子邮件,即使在许多看似安全的Web服务器配置下也是如此。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章