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服務器配置下也是如此。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章