“Django/docs/3.0.x/ref/middleware”的版本间差异

来自菜鸟教程
Django/docs/3.0.x/ref/middleware
跳转至:导航、​搜索
(autoload)
 
(Page commit)
 
第1行: 第1行:
 +
{{DISPLAYTITLE:中间件 — Django 文档}}
 
<div id="module-django.middleware" class="section">
 
<div id="module-django.middleware" class="section">
  
第4行: 第5行:
 
= 中间件 =
 
= 中间件 =
  
This document explains all middleware components that come with Django. For
+
本文档解释了 Django 附带的所有中间件组件。 有关如何使用它们以及如何编写自己的中间件的信息,请参阅 [[../../topics/http/middleware|中间件使用指南]]
information on how to use them and how to write your own middleware, see
 
the [[../../topics/http/middleware|<span class="doc">middleware usage guide</span>]].
 
  
 
<div id="available-middleware" class="section">
 
<div id="available-middleware" class="section">
  
== Available middleware ==
+
== 可用的中间件 ==
  
 
<div id="module-django.middleware.cache" class="section">
 
<div id="module-django.middleware.cache" class="section">
  
 
<span id="cache-middleware"></span>
 
<span id="cache-middleware"></span>
=== Cache middleware ===
+
=== 缓存中间件 ===
  
; ''class'' <code>UpdateCacheMiddleware</code>
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">UpdateCacheMiddleware</span></span>
 
:  
 
:  
  
; ''class'' <code>FetchFromCacheMiddleware</code>
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">FetchFromCacheMiddleware</span></span>
 
:  
 
:  
  
Enable the site-wide cache. If these are enabled, each Django-powered page will
+
启用站点范围的缓存。 如果启用这些,每个 Django 驱动的页面将被缓存,只要 [[#id1|:setting:`CACHE_MIDDLEWARE_SECONDS`]] 设置定义。 请参阅 [[../../topics/cache|缓存文档]]
be cached for as long as the [[../settings#std-setting-CACHE_MIDDLEWARE_SECONDS|<code>CACHE_MIDDLEWARE_SECONDS</code>]] setting
 
defines. See the [[../../topics/cache|<span class="doc">cache documentation</span>]].
 
  
  
第32行: 第29行:
  
 
<span id="common-middleware"></span>
 
<span id="common-middleware"></span>
=== &quot;Common&quot; middleware ===
+
=== “通用”中间件 ===
  
; ''class'' <code>CommonMiddleware</code>
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">CommonMiddleware</span></span>
 
:  
 
:  
  
Adds a few conveniences for perfectionists:
+
为完美主义者增加了一些便利:
  
 
<ul>
 
<ul>
<li><p>Forbids access to user agents in the [[../settings#std-setting-DISALLOWED_USER_AGENTS|<code>DISALLOWED_USER_AGENTS</code>]]
+
<li><p>禁止访问 [[#id3|:setting:`DISALLOWED_USER_AGENTS`]] 设置中的用户代理,该设置应该是已编译的正则表达式对象列表。</p></li>
setting, which should be a list of compiled regular expression objects.</p></li>
+
<li><p>根据 [[#id5|:setting:`APPEND_SLASH`]] [[#id7|:setting:`PREPEND_WWW`]] 设置执行 URL 重写。</p>
<li><p>Performs URL rewriting based on the [[../settings#std-setting-APPEND_SLASH|<code>APPEND_SLASH</code>]] and
+
<p>如果 [[#id9|:setting:`APPEND_SLASH`]] <code>True</code> 并且初始 URL 不以斜杠结尾,并且在 URLconf 中找不到,则通过附加一个新 URL 形成斜线在最后。 如果在 URLconf 中找到了这个新 URL,那么 Django 会将请求重定向到这个新 URL。 否则,将照常处理初始 URL。</p>
[[../settings#std-setting-PREPEND_WWW|<code>PREPEND_WWW</code>]] settings.</p>
+
<p>例如,如果 <code>foo.com/bar</code> 没有有效的 URL 模式,但 ''do 有'' 的有效模式,则 <code>foo.com/bar</code> 将被重定向到 <code>foo.com/bar/</code> X148X]。</p>
<p>If [[../settings#std-setting-APPEND_SLASH|<code>APPEND_SLASH</code>]] is <code>True</code> and the initial URL doesn't end
+
<p>如果 [[#id11|:setting:`PREPEND_WWW`]] <code>True</code>,则缺少前导“www”的 URL。 将被重定向到以“www”开头的相同 URL。</p>
with a slash, and it is not found in the URLconf, then a new URL is
+
<p>这两个选项都用于规范化 URL。 其理念是每个 URL 都应存在于一个且仅一个位置。 从技术上讲,URL <code>foo.com/bar</code> <code>foo.com/bar/</code> 不同——搜索引擎索引器会将它们视为单独的 URL——因此最佳做法是规范化 URL。</p></li>
formed by appending a slash at the end. If this new URL is found in the
+
<li><p>为非流响应设置 <code>Content-Length</code> 标头。</p></li></ul>
URLconf, then Django redirects the request to this new URL. Otherwise,
 
the initial URL is processed as usual.</p>
 
<p>For example, <code>foo.com/bar</code> will be redirected to <code>foo.com/bar/</code> if
 
you don't have a valid URL pattern for <code>foo.com/bar</code> but ''do'' have a
 
valid pattern for <code>foo.com/bar/</code>.</p>
 
<p>If [[../settings#std-setting-PREPEND_WWW|<code>PREPEND_WWW</code>]] is <code>True</code>, URLs that lack a leading &quot;www.&quot;
 
will be redirected to the same URL with a leading &quot;www.&quot;</p>
 
<p>Both of these options are meant to normalize URLs. The philosophy is that
 
each URL should exist in one, and only one, place. Technically a URL
 
<code>foo.com/bar</code> is distinct from <code>foo.com/bar/</code> -- a search-engine
 
indexer would treat them as separate URLs -- so it's best practice to
 
normalize URLs.</p></li>
 
<li><p>Sets the <code>Content-Length</code> header for non-streaming responses.</p></li></ul>
 
  
; <code>CommonMiddleware.</code><code>response_redirect_class</code>
+
; <span class="sig-prename descclassname"><span class="pre">CommonMiddleware.</span></span><span class="sig-name descname"><span class="pre">response_redirect_class</span></span>
 
:  
 
:  
  
Defaults to [[../request-response#django.http|<code>HttpResponsePermanentRedirect</code>]]. Subclass
+
默认为 [[../request-response#django.http|HttpResponsePermanentRedirect]]。 子类 <code>CommonMiddleware</code> 并覆盖该属性以自定义中间件发出的重定向。
<code>CommonMiddleware</code> and override the attribute to customize the redirects
 
issued by the middleware.
 
  
; ''class'' <code>BrokenLinkEmailsMiddleware</code>
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">BrokenLinkEmailsMiddleware</span></span>
 
:  
 
:  
  
* Sends broken link notification emails to [[../settings#std-setting-MANAGERS|<code>MANAGERS</code>]] (see [[../../howto/error-reporting|<span class="doc">发送错误</span>]]).
+
* [[#id13|:setting:`MANAGERS`]] 发送断开链接通知电子邮件(请参阅 [[../../howto/error-reporting|错误报告]] )。
  
  
第78行: 第60行:
  
 
<span id="gzip-middleware"></span>
 
<span id="gzip-middleware"></span>
=== GZip middleware ===
+
=== GZip中间件 ===
  
; ''class'' <code>GZipMiddleware</code>
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">GZipMiddleware</span></span>
 
:  
 
:  
  
第87行: 第69行:
 
警告
 
警告
  
Security researchers recently revealed that when compression techniques
+
安全研究人员最近透露,当在网站上使用压缩技术(包括 <code>GZipMiddleware</code>)时,该网站可能会受到多种可能的攻击。 在您的站点上使用 <code>GZipMiddleware</code> 之前,您应该非常仔细地考虑您是否受到这些攻击。 如果你在 ''任何'' 怀疑你是否受到影响,你应该避免使用 <code>GZipMiddleware</code>。 有关更多详细信息,请参阅 [http://breachattack.com/resources/BREACH%20-%20SSL,%20gone%20in%2030%20seconds.pdf the BREACH 论文 (PDF)] [http://breachattack.com breachattack.com]
(including <code>GZipMiddleware</code>) are used on a website, the site may become
 
exposed to a number of possible attacks. Before using <code>GZipMiddleware</code> on
 
your site, you should consider very carefully whether you are subject to
 
these attacks. If you're in ''any'' doubt about whether you're affected, you
 
should avoid using <code>GZipMiddleware</code>. For more details, see the [http://breachattack.com/resources/BREACH%20-%20SSL,%20gone%20in%2030%20seconds.pdf the BREACH
 
paper (PDF)] and [http://breachattack.com breachattack.com].
 
  
  
 
</div>
 
</div>
The <code>django.middleware.gzip.GZipMiddleware</code> compresses content for browsers
+
<code>django.middleware.gzip.GZipMiddleware</code> 为理解 GZip 压缩的浏览器(所有现代浏览器)压缩内容。
that understand GZip compression (all modern browsers).
 
  
This middleware should be placed before any other middleware that need to
+
该中间件应放置在需要读取或写入响应正文的任何其他中间件之前,以便随后进行压缩。
read or write the response body so that compression happens afterward.
 
  
It will NOT compress content if any of the following are true:
+
如果以下任何一项为真,它将不会压缩内容:
  
* The content body is less than 200 bytes long.
+
* 内容主体长度小于 200 字节。
* The response has already set the <code>Content-Encoding</code> header.
+
* 响应已经设置了 <code>Content-Encoding</code> 标头。
* The request (the browser) hasn't sent an <code>Accept-Encoding</code> header containing <code>gzip</code>.
+
* 请求(浏览器)尚未发送包含 <code>gzip</code> <code>Accept-Encoding</code> 标头。
  
If the response has an <code>ETag</code> header, the ETag is made weak to comply with
+
如果响应具有 <code>ETag</code> 标头,则 ETag 会变弱以符合 <span id="index-0" class="target"></span>[https://tools.ietf.org/html/rfc7232.html#section-2.1 RFC 7232#section-2.1]
<span id="index-0" class="target"></span>[https://tools.ietf.org/html/rfc7232.html#section-2.1 '''RFC 7232#section-2.1'''].
 
  
You can apply GZip compression to individual views using the
+
您可以使用 [[../../topics/http/decorators#django.views.decorators.gzip|gzip_page()]] 装饰器将 GZip 压缩应用于单个视图。
[[../../topics/http/decorators#django.views.decorators.gzip|<code>gzip_page()</code>]] decorator.
 
  
  
第120行: 第92行:
  
 
<span id="conditional-get-middleware"></span>
 
<span id="conditional-get-middleware"></span>
=== Conditional GET middleware ===
+
=== 条件获取中间件 ===
  
; ''class'' <code>ConditionalGetMiddleware</code>
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">ConditionalGetMiddleware</span></span>
 
:  
 
:  
  
Handles conditional GET operations. If the response doesn't have an <code>ETag</code>
+
处理条件 GET 操作。 如果响应没有 <code>ETag</code> 标头,中间件会根据需要添加一个。 如果响应具有 <code>ETag</code> <code>Last-Modified</code> 标头,并且请求具有 <code>If-None-Match</code> <code>If-Modified-Since</code>,则响应被替换为 [[../request-response#django.http|HttpResponseNotModified]] ]。
header, the middleware adds one if needed. If the response has an <code>ETag</code> or
 
<code>Last-Modified</code> header, and the request has <code>If-None-Match</code> or
 
<code>If-Modified-Since</code>, the response is replaced by an
 
[[../request-response#django.http|<code>HttpResponseNotModified</code>]].
 
  
  
第136行: 第104行:
  
 
<span id="locale-middleware"></span>
 
<span id="locale-middleware"></span>
=== Locale middleware ===
+
=== 语言环境中间件 ===
  
; ''class'' <code>LocaleMiddleware</code>
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">LocaleMiddleware</span></span>
 
:  
 
:  
  
Enables language selection based on data from the request. It customizes
+
根据请求中的数据启用语言选择。 它为每个用户定制内容。 请参阅 [[../../topics/i18n/translation|国际化文档]]
content for each user. See the [[../../topics/i18n/translation|<span class="doc">internationalization documentation</span>]].
 
  
; <code>LocaleMiddleware.</code><code>response_redirect_class</code>
+
; <span class="sig-prename descclassname"><span class="pre">LocaleMiddleware.</span></span><span class="sig-name descname"><span class="pre">response_redirect_class</span></span>
 
:  
 
:  
  
Defaults to [[../request-response#django.http|<code>HttpResponseRedirect</code>]]. Subclass
+
默认为 [[../request-response#django.http|HttpResponseRedirect]]。 子类 <code>LocaleMiddleware</code> 并覆盖该属性以自定义中间件发出的重定向。
<code>LocaleMiddleware</code> and override the attribute to customize the redirects
 
issued by the middleware.
 
  
  
第156行: 第121行:
  
 
<span id="message-middleware"></span>
 
<span id="message-middleware"></span>
=== Message middleware ===
+
=== 消息中间件 ===
  
; ''class'' <code>MessageMiddleware</code>[[../_modules/django/contrib/messages/middleware.html#MessageMiddleware|<span class="viewcode-link">[源代码]</span>]]
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">MessageMiddleware</span></span>
 
:  
 
:  
  
Enables cookie- and session-based message support. See the
+
启用基于 cookie 和会话的消息支持。 请参阅 [[../contrib/messages|消息文档]]
[[../contrib/messages|<span class="doc">messages documentation</span>]].
 
  
  
第168行: 第132行:
 
<div id="module-django.middleware.security" class="section">
 
<div id="module-django.middleware.security" class="section">
  
<span id="id1"></span><span id="security-middleware"></span>
+
<span id="id15"></span><span id="security-middleware"></span>
=== Security middleware ===
+
=== 安全中间件 ===
  
 
<div class="admonition warning">
 
<div class="admonition warning">
第175行: 第139行:
 
警告
 
警告
  
If your deployment situation allows, it's usually a good idea to have your
+
如果您的部署情况允许,让您的前端 Web 服务器执行 <code>SecurityMiddleware</code> 提供的功能通常是个好主意。 这样,如果有 Django 不提供的请求(例如静态媒体或用户上传的文件),它们将具有与对 Django 应用程序的请求相同的保护。
front-end Web server perform the functionality provided by the
 
<code>SecurityMiddleware</code>. That way, if there are requests that aren't served
 
by Django (such as static media or user-uploaded files), they will have
 
the same protections as requests to your Django application.
 
  
  
 
</div>
 
</div>
; ''class'' <code>SecurityMiddleware</code>
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">SecurityMiddleware</span></span>
 
:  
 
:  
  
The <code>django.middleware.security.SecurityMiddleware</code> provides several security
+
<code>django.middleware.security.SecurityMiddleware</code> 为请求/响应周期提供了多项安全增强功能。 每个都可以通过设置独立启用或禁用。
enhancements to the request/response cycle. Each one can be independently
 
enabled or disabled with a setting.
 
  
* [[../settings#std-setting-SECURE_BROWSER_XSS_FILTER|<code>SECURE_BROWSER_XSS_FILTER</code>]]
+
* [[#id16|<span id="id17" class="problematic">:设置:`SECURE_BROWSER_XSS_FILTER`</span>]]
* [[../settings#std-setting-SECURE_CONTENT_TYPE_NOSNIFF|<code>SECURE_CONTENT_TYPE_NOSNIFF</code>]]
+
* [[#id18|<span id="id19" class="problematic">:设置:`SECURE_CONTENT_TYPE_NOSNIFF`</span>]]
* [[../settings#std-setting-SECURE_HSTS_INCLUDE_SUBDOMAINS|<code>SECURE_HSTS_INCLUDE_SUBDOMAINS</code>]]
+
* [[#id20|<span id="id21" class="problematic">:设置:`SECURE_HSTS_INCLUDE_SUBDOMAINS`</span>]]
* [[../settings#std-setting-SECURE_HSTS_PRELOAD|<code>SECURE_HSTS_PRELOAD</code>]]
+
* [[#id22|<span id="id23" class="problematic">:设置:`SECURE_HSTS_PRELOAD`</span>]]
* [[../settings#std-setting-SECURE_HSTS_SECONDS|<code>SECURE_HSTS_SECONDS</code>]]
+
* [[#id24|<span id="id25" class="problematic">:设置:`SECURE_HSTS_SECONDS`</span>]]
* [[../settings#std-setting-SECURE_REDIRECT_EXEMPT|<code>SECURE_REDIRECT_EXEMPT</code>]]
+
* [[#id26|<span id="id27" class="problematic">:设置:`SECURE_REDIRECT_EXEMPT`</span>]]
* [[../settings#std-setting-SECURE_REFERRER_POLICY|<code>SECURE_REFERRER_POLICY</code>]]
+
* [[#id28|<span id="id29" class="problematic">:设置:`SECURE_REFERRER_POLICY`</span>]]
* [[../settings#std-setting-SECURE_SSL_HOST|<code>SECURE_SSL_HOST</code>]]
+
* [[#id30|<span id="id31" class="problematic">:设置:`SECURE_SSL_HOST`</span>]]
* [[../settings#std-setting-SECURE_SSL_REDIRECT|<code>SECURE_SSL_REDIRECT</code>]]
+
* [[#id32|<span id="id33" class="problematic">:设置:`SECURE_SSL_REDIRECT`</span>]]
  
 
<div id="http-strict-transport-security" class="section">
 
<div id="http-strict-transport-security" class="section">
  
<span id="id2"></span>
+
<span id="id34"></span>
==== HTTP Strict Transport Security ====
+
==== HTTP 严格传输安全 ====
  
For sites that should only be accessed over HTTPS, you can instruct modern
+
对于只能通过 HTTPS 访问的站点,您可以通过设置 [https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security “Strict-Transport-Security” 标头] “Strict-Transport-Security” 标头,指示现代浏览器拒绝通过不安全连接(在给定时间段内)连接到您的域名X234X]。 这减少了您遭受某些 SSL 剥离中间人 (MITM) 攻击的风险。
browsers to refuse to connect to your domain name via an insecure connection
 
(for a given period of time) by setting the [https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security &quot;Strict-Transport-Security&quot;
 
header]. This reduces your exposure to some SSL-stripping man-in-the-middle
 
(MITM) attacks.
 
  
<code>SecurityMiddleware</code> will set this header for you on all HTTPS responses if
+
如果您将 [[#id35|:setting:`SECURE_HSTS_SECONDS`]] 设置为非零整数值,<code>SecurityMiddleware</code> 将在所有 HTTPS 响应中为您设置此标头。
you set the [[../settings#std-setting-SECURE_HSTS_SECONDS|<code>SECURE_HSTS_SECONDS</code>]] setting to a non-zero integer value.
 
  
When enabling HSTS, it's a good idea to first use a small value for testing,
+
启用 HSTS 时,最好先使用较小的值进行测试,例如, [[#id37|:设置:`SECURE_HSTS_SECONDS = 3600 `]] 一小时。 每次 Web 浏览器从您的站点看到 HSTS 标头时,它都会在给定的时间段内拒绝与您的域进行非安全(使用 HTTP)通信。 一旦您确认所有资产都在您的网站上安全地提供(即 HSTS 没有破坏任何东西),增加这个值是个好主意,这样不频繁的访问者将受到保护(31536000 秒,即 1 年,很常见)。
for example, [[../settings#std-setting-SECURE_HSTS_SECONDS|<code>SECURE_HSTS_SECONDS = 3600</code>]] for one
 
hour. Each time a Web browser sees the HSTS header from your site, it will
 
refuse to communicate non-securely (using HTTP) with your domain for the given
 
period of time. Once you confirm that all assets are served securely on your
 
site (i.e. HSTS didn't break anything), it's a good idea to increase this value
 
so that infrequent visitors will be protected (31536000 seconds, i.e. 1 year,
 
is common).
 
  
Additionally, if you set the [[../settings#std-setting-SECURE_HSTS_INCLUDE_SUBDOMAINS|<code>SECURE_HSTS_INCLUDE_SUBDOMAINS</code>]] setting
+
此外,如果您将 [[#id39|:setting:`SECURE_HSTS_INCLUDE_SUBDOMAINS`]] 设置为 <code>True</code><code>SecurityMiddleware</code> 会将 <code>includeSubDomains</code> 指令添加到 [X15] ] 标题。 这是推荐的(假设所有子域都只使用 HTTPS 提供服务),否则您的站点可能仍然容易通过与子域的不安全连接而受到攻击。
to <code>True</code>, <code>SecurityMiddleware</code> will add the <code>includeSubDomains</code> directive
 
to the <code>Strict-Transport-Security</code> header. This is recommended (assuming all
 
subdomains are served exclusively using HTTPS), otherwise your site may still
 
be vulnerable via an insecure connection to a subdomain.
 
  
If you wish to submit your site to the [https://hstspreload.org/ browser preload list], set the
+
如果您希望将您的站点提交到 [https://hstspreload.org/ 浏览器预加载列表] ,请将 [[#id41|:setting:`SECURE_HSTS_PRELOAD`]] 设置为 <code>True</code>。 将 <code>preload</code> 指令附加到 <code>Strict-Transport-Security</code> 标头。
[[../settings#std-setting-SECURE_HSTS_PRELOAD|<code>SECURE_HSTS_PRELOAD</code>]] setting to <code>True</code>. That appends the
 
<code>preload</code> directive to the <code>Strict-Transport-Security</code> header.
 
  
 
<div class="admonition warning">
 
<div class="admonition warning">
第237行: 第177行:
 
警告
 
警告
  
The HSTS policy applies to your entire domain, not just the URL of the
+
HSTS 策略适用于您的整个域,而不仅仅是您设置标头的响应的 URL。 因此,仅当您的整个域仅通过 HTTPS 提供服务时才应使用它。
response that you set the header on. Therefore, you should only use it if
 
your entire domain is served via HTTPS only.
 
  
Browsers properly respecting the HSTS header will refuse to allow users to
+
正确遵守 HSTS 标头的浏览器将拒绝允许用户绕过警告并连接到具有过期、自签名或其他无效 SSL 证书的站点。 如果您使用 HSTS,请确保您的证书状态良好并保持这种状态!
bypass warnings and connect to a site with an expired, self-signed, or
 
otherwise invalid SSL certificate. If you use HSTS, make sure your
 
certificates are in good shape and stay that way!
 
  
  
第250行: 第185行:
 
<div class="admonition note">
 
<div class="admonition note">
  
注解
+
笔记
  
If you are deployed behind a load-balancer or reverse-proxy server, and the
+
如果您部署在负载平衡器或反向代理服务器之后,并且 <code>Strict-Transport-Security</code> 标头未添加到您的响应中,则可能是因为 Django 没有意识到它处于安全连接上; 您可能需要设置 [[#id43|:setting:`SECURE_PROXY_SSL_HEADER`]] 设置。
<code>Strict-Transport-Security</code> header is not being added to your responses,
 
it may be because Django doesn't realize that it's on a secure connection;
 
you may need to set the [[../settings#std-setting-SECURE_PROXY_SSL_HEADER|<code>SECURE_PROXY_SSL_HEADER</code>]] setting.
 
  
  
第263行: 第195行:
 
<div id="referrer-policy" class="section">
 
<div id="referrer-policy" class="section">
  
<span id="id4"></span>
+
<span id="id46"></span>
==== Referrer Policy ====
+
==== 推荐人政策 ====
  
 
<div class="versionadded">
 
<div class="versionadded">
  
 +
<span class="versionmodified added">3.0 版中的新功能。</span>
  
  
 
</div>
 
</div>
Browsers use [https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referer the Referer header] as a way to send information to a site
+
浏览器使用 [https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referer 引用标头] 作为向站点发送有关用户如何到达那里的信息的一种方式。 当用户单击链接时,浏览器将发送链接页面的完整 URL 作为引用者。 虽然这对某些目的很有用——比如找出谁链接到你的网站——但它也可能会通过通知一个网站用户正在访问另一个网站而引起隐私问题。
about how users got there. When a user clicks a link, the browser will send the
 
full URL of the linking page as the referrer. While this can be useful for some
 
purposes -- like figuring out who's linking to your site -- it also can cause
 
privacy concerns by informing one site that a user was visiting another site.
 
  
Some browsers have the ability to accept hints about whether they should send
+
某些浏览器能够接受有关在用户单击链接时是否应该发送 HTTP <code>Referer</code> 标头的提示; 此提示是通过 [https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy 引用策略标头] 提供的。 此标头可以向浏览器建议以下三种行为中的任何一种:
the HTTP <code>Referer</code> header when a user clicks a link; this hint is provided
 
via [https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy the Referrer-Policy header]. This header can suggest any of three
 
behaviors to browsers:
 
  
* Full URL: send the entire URL in the <code>Referer</code> header. For example, if the user is visiting <code>https://example.com/page.html</code>, the <code>Referer</code> header would contain <code>&quot;https://example.com/page.html&quot;</code>.
+
* 完整 URL:在 <code>Referer</code> 标头中发送整个 URL。 例如,如果用户正在访问 <code>https://example.com/page.html</code>,则 <code>Referer</code> 标头将包含 <code>&quot;https://example.com/page.html&quot;</code>
* Origin only: send only the &quot;origin&quot; in the referrer. The origin consists of the scheme, host and (optionally) port number. For example, if the user is visiting <code>https://example.com/page.html</code>, the origin would be <code>https://example.com/</code>.
+
* 仅来源:仅发送推荐人中的“来源”。 来源由方案、主机和(可选)端口号组成。 例如,如果用户正在访问 <code>https://example.com/page.html</code>,则原点将是 <code>https://example.com/</code>
* No referrer: do not send a <code>Referer</code> header at all.
+
* 无引用:根本不发送 <code>Referer</code> 标头。
  
There are two types of conditions this header can tell a browser to watch out
+
此标头可以告诉浏览器注意两种类型的条件:
for:
 
  
* Same-origin versus cross-origin: a link from <code>https://example.com/1.html</code> to <code>https://example.com/2.html</code> is same-origin. A link from <code>https://example.com/page.html</code> to <code>https://not.example.com/page.html</code> is cross-origin.
+
* 同源与跨源:从 <code>https://example.com/1.html</code> <code>https://example.com/2.html</code> 的链接是同源的。 从 <code>https://example.com/page.html</code> <code>https://not.example.com/page.html</code> 的链接是跨域的。
* Protocol downgrade: a downgrade occurs if the page containing the link is served via HTTPS, but the page being linked to is not served via HTTPS.
+
* 协议降级:如果包含链接的页面通过 HTTPS 提供服务,但链接到的页面不是通过 HTTPS 提供服务,则会发生降级。
  
 
<div class="admonition warning">
 
<div class="admonition warning">
第296行: 第221行:
 
警告
 
警告
  
When your site is served via HTTPS, [[../csrf#using-csrf|<span class="std std-ref">Django's CSRF protection system</span>]] requires the <code>Referer</code> header to be present, so completely
+
当您的站点通过 HTTPS 提供服务时,[[../csrf#using-csrf|Django CSRF 保护系统]] 要求存在 <code>Referer</code> 标头,因此完全禁用 <code>Referer</code> 标头会干扰 CSRF 保护。 要获得禁用 <code>Referer</code> 标头的大部分好处,同时保持 CSRF 保护,请考虑仅启用同源引用。
disabling the <code>Referer</code> header will interfere with CSRF protection. To
 
gain most of the benefits of disabling <code>Referer</code> headers while also
 
keeping CSRF protection, consider enabling only same-origin referrers.
 
  
  
 
</div>
 
</div>
<code>SecurityMiddleware</code> can set the <code>Referrer-Policy</code> header for you, based on
+
<code>SecurityMiddleware</code> 可以根据 [[#id49|:setting:`SECURE_REFERRER_POLICY`]] 设置为您设置 <code>Referrer-Policy</code> 标头(注意拼写:浏览器发送 <code>Referer</code> 标头当用户单击链接,但指示浏览器是否这样做的标题拼写为 <code>Referrer-Policy</code>)。 此设置的有效值为:
the the [[../settings#std-setting-SECURE_REFERRER_POLICY|<code>SECURE_REFERRER_POLICY</code>]] setting (note spelling: browsers send
 
a <code>Referer</code> header when a user clicks a link, but the header instructing a
 
browser whether to do so is spelled <code>Referrer-Policy</code>). The valid values for
 
this setting are:
 
  
 
; <code>no-referrer</code>
 
; <code>no-referrer</code>
: Instructs the browser to send no referrer for links clicked on this site.
+
: 指示浏览器不为在此站点上单击的链接发送引荐来源网址。
 
; <code>no-referrer-when-downgrade</code>
 
; <code>no-referrer-when-downgrade</code>
: Instructs the browser to send a full URL as the referrer, but only when no protocol downgrade occurs.
+
: 指示浏览器发送完整的 URL 作为引用者,但仅当没有发生协议降级时。
 
; <code>origin</code>
 
; <code>origin</code>
: Instructs the browser to send only the origin, not the full URL, as the referrer.
+
: 指示浏览器仅发送来源,而不是完整的 URL,作为引用者。
 
; <code>origin-when-cross-origin</code>
 
; <code>origin-when-cross-origin</code>
: Instructs the browser to send the full URL as the referrer for same-origin links, and only the origin for cross-origin links.
+
: 指示浏览器发送完整的 URL 作为同源链接的引用来源,并且只发送跨源链接的来源。
 
; <code>same-origin</code>
 
; <code>same-origin</code>
: Instructs the browser to send a full URL, but only for same-origin links. No referrer will be sent for cross-origin links.
+
: 指示浏览器发送完整的 URL,但仅用于同源链接。 不会为跨源链接发送推荐人。
 
; <code>strict-origin</code>
 
; <code>strict-origin</code>
: Instructs the browser to send only the origin, not the full URL, and to send no referrer when a protocol downgrade occurs.
+
: 指示浏览器仅发送源,而不是完整的 URL,并且在发生协议降级时不发送引用。
 
; <code>strict-origin-when-cross-origin</code>
 
; <code>strict-origin-when-cross-origin</code>
: Instructs the browser to send the full URL when the link is same-origin and no protocol downgrade occurs; send only the origin when the link is cross-origin and no protocol downgrade occurs; and no referrer when a protocol downgrade occurs.
+
: 当链接是同源的并且没有发生协议降级时,指示浏览器发送完整的URL; 当链路是跨域的并且没有发生协议降级时,只发送源; 并且在发生协议降级时没有引用者。
 
; <code>unsafe-url</code>
 
; <code>unsafe-url</code>
: Instructs the browser to always send the full URL as the referrer.
+
: 指示浏览器始终将完整 URL 作为引用者发送。
  
 
<div class="admonition-unknown-policy-values admonition">
 
<div class="admonition-unknown-policy-values admonition">
  
Unknown Policy Values
+
未知的策略值
  
Where a policy value is [https://w3c.github.io/webappsec-referrer-policy/#unknown-policy-values unknown] by a user agent, it is possible to
+
如果用户代理的策略值为 [https://w3c.github.io/webappsec-referrer-policy/#unknown-policy-values unknown],则可以指定多个策略值以提供回退。 最后一个被理解的指定值优先。 为了支持这一点,可以将可迭代或逗号分隔的字符串与 [[#id51|:setting:`SECURE_REFERRER_POLICY`]] 一起使用。
specify multiple policy values to provide a fallback. The last specified
 
value that is understood takes precedence. To support this, an iterable or
 
comma-separated string can be used with [[../settings#std-setting-SECURE_REFERRER_POLICY|<code>SECURE_REFERRER_POLICY</code>]].
 
  
  
第342行: 第257行:
  
 
<span id="x-content-type-options"></span>
 
<span id="x-content-type-options"></span>
==== <code>X-Content-Type-Options: nosniff</code> ====
+
==== X-Content-Type-Options: nosniff ====
  
Some browsers will try to guess the content types of the assets that they
+
一些浏览器会尝试猜测它们获取的资产的内容类型,覆盖 <code>Content-Type</code> 标头。 虽然这有助于显示服务器配置不当的站点,但它也可能带来安全风险。
fetch, overriding the <code>Content-Type</code> header. While this can help display
 
sites with improperly configured servers, it can also pose a security
 
risk.
 
  
If your site serves user-uploaded files, a malicious user could upload a
+
如果您的站点提供用户上传的文件,恶意用户可能会上传一个特制的文件,当您认为它是无害的时,浏览器会将其解释为 HTML 或 JavaScript。
specially-crafted file that would be interpreted as HTML or JavaScript by
 
the browser when you expected it to be something harmless.
 
  
To prevent the browser from guessing the content type and force it to
+
为了防止浏览器猜测内容类型并强制它始终使用 <code>Content-Type</code> 标头中提供的类型,您可以传递 [https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options X-Content-Type-Options: nosniff] 标头。 <code>SecurityMiddleware</code> 将对所有响应执行此操作,如果 [[#id54|:setting:`SECURE_CONTENT_TYPE_NOSNIFF`]] 设置为 <code>True</code>
always use the type provided in the <code>Content-Type</code> header, you can pass
 
the [https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options X-Content-Type-Options: nosniff] header. <code>SecurityMiddleware</code> will
 
do this for all responses if the [[../settings#std-setting-SECURE_CONTENT_TYPE_NOSNIFF|<code>SECURE_CONTENT_TYPE_NOSNIFF</code>]] setting
 
is <code>True</code>.
 
  
Note that in most deployment situations where Django isn't involved in serving
+
请注意,在 Django 不参与为用户上传的文件提供服务的大多数部署情况下,此设置对您没有帮助。 例如,如果您的 [[#id56|:setting:`MEDIA_URL`]] 直接由您的前端 Web 服务器(nginx、Apache 等)提供服务,那么您需要在那里设置此标头。 另一方面,如果您使用 Django 执行诸如需要授权才能下载文件之类的操作,并且您无法使用 Web 服务器设置标头,则此设置将很有用。
user-uploaded files, this setting won't help you. For example, if your
 
[[../settings#std-setting-MEDIA_URL|<code>MEDIA_URL</code>]] is served directly by your front-end Web server (nginx,
 
Apache, etc.) then you'd want to set this header there. On the other hand, if
 
you are using Django to do something like require authorization in order to
 
download files and you cannot set the header using your Web server, this
 
setting will be useful.
 
  
  
第372行: 第272行:
  
 
<span id="x-xss-protection"></span>
 
<span id="x-xss-protection"></span>
==== <code>X-XSS-Protection: 1; mode=block</code> ====
+
==== X-XSS-Protection: 1; mode=block ====
  
Some browsers have the ability to block content that appears to be an [https://en.wikipedia.org/wiki/Cross-site_scripting XSS
+
某些浏览器能够阻止看起来像是 [https://en.wikipedia.org/wiki/Cross-site_scripting XSS 攻击] 的内容。 它们通过在页面的 GET POST 参数中查找 JavaScript 内容来工作。 如果 JavaScript 在服务器的响应中被重播,页面将被阻止呈现并显示错误页面。
attack]. They work by looking for JavaScript content in the GET or POST
 
parameters of a page. If the JavaScript is replayed in the server's response,
 
the page is blocked from rendering and an error page is shown instead.
 
  
The [https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection X-XSS-Protection header] is used to control the operation of the
+
[https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection X-XSS-Protection头]用于控制XSS过滤器的操作。
XSS filter.
 
  
To enable the XSS filter in the browser, and force it to always block
+
要在浏览器中启用 XSS 过滤器,并强制它始终阻止可疑的 XSS 攻击,您可以传递 <code>X-XSS-Protection: 1; mode=block</code> 标头。 如果 [[#id59|:setting:`SECURE_BROWSER_XSS_FILTER`]] 设置为 <code>True</code><code>SecurityMiddleware</code> 将对所有响应执行此操作。
suspected XSS attacks, you can pass the <code>X-XSS-Protection: 1; mode=block</code>
 
header. <code>SecurityMiddleware</code> will do this for all responses if the
 
[[../settings#std-setting-SECURE_BROWSER_XSS_FILTER|<code>SECURE_BROWSER_XSS_FILTER</code>]] setting is <code>True</code>.
 
  
 
<div class="admonition warning">
 
<div class="admonition warning">
第391行: 第284行:
 
警告
 
警告
  
The browser XSS filter is a useful defense measure, but must not be
+
浏览器 XSS 过滤器是一种有用的防御措施,但不能完全依赖。 它不能检测所有 XSS 攻击,也不是所有浏览器都支持标头。 确保您仍在 [[../../topics/security#cross-site-scripting|验证和清理]] 所有输入以防止 XSS 攻击。
relied upon exclusively. It cannot detect all XSS attacks and not all
 
browsers support the header. Ensure you are still [[../../topics/security#cross-site-scripting|<span class="std std-ref">validating and
 
sanitizing</span>]] all input to prevent XSS attacks.
 
  
  
第402行: 第292行:
 
<div id="ssl-redirect" class="section">
 
<div id="ssl-redirect" class="section">
  
<span id="id10"></span>
+
<span id="id62"></span>
==== SSL Redirect ====
+
==== SSL 重定向 ====
  
If your site offers both HTTP and HTTPS connections, most users will end up
+
如果您的站点同时提供 HTTP HTTPS 连接,默认情况下大多数用户最终会使用不安全的连接。 为了获得最佳安全性,您应该将所有 HTTP 连接重定向到 HTTPS。
with an unsecured connection by default. For best security, you should redirect
 
all HTTP connections to HTTPS.
 
  
If you set the [[../settings#std-setting-SECURE_SSL_REDIRECT|<code>SECURE_SSL_REDIRECT</code>]] setting to True,
+
如果您将 [[#id63|:setting:`SECURE_SSL_REDIRECT`]] 设置为 True,<code>SecurityMiddleware</code> 将永久 (HTTP 301) 将所有 HTTP 连接重定向到 HTTPS。
<code>SecurityMiddleware</code> will permanently (HTTP 301) redirect all HTTP
 
connections to HTTPS.
 
  
 
<div class="admonition note">
 
<div class="admonition note">
  
注解
+
笔记
  
For performance reasons, it's preferable to do these redirects outside of
+
出于性能原因,最好在 Django 之外、在前端负载平衡器或反向代理服务器(如 [https://nginx.org nginx])中进行这些重定向。 [[#id65|:setting:`SECURE_SSL_REDIRECT`]] 适用于无法选择的部署情况。
Django, in a front-end load balancer or reverse-proxy server such as
 
[https://nginx.org nginx]. [[../settings#std-setting-SECURE_SSL_REDIRECT|<code>SECURE_SSL_REDIRECT</code>]] is intended for the deployment
 
situations where this isn't an option.
 
  
  
 
</div>
 
</div>
If the [[../settings#std-setting-SECURE_SSL_HOST|<code>SECURE_SSL_HOST</code>]] setting has a value, all redirects will be
+
如果 [[#id67|:setting:`SECURE_SSL_HOST`]] 设置具有值,则所有重定向都将发送到该主机而不是最初请求的主机。
sent to that host instead of the originally-requested host.
 
  
If there are a few pages on your site that should be available over HTTP, and
+
如果您的站点上有几个页面应该可以通过 HTTP 访问,而不是重定向到 HTTPS,您可以在 [[#id69|:setting:`SECURE_REDIRECT_EXEMPT`]] 设置中列出与这些 URL 匹配的正则表达式。
not redirected to HTTPS, you can list regular expressions to match those URLs
 
in the [[../settings#std-setting-SECURE_REDIRECT_EXEMPT|<code>SECURE_REDIRECT_EXEMPT</code>]] setting.
 
  
 
<div class="admonition note">
 
<div class="admonition note">
  
注解
+
笔记
  
If you are deployed behind a load-balancer or reverse-proxy server and
+
如果您部署在负载均衡器或反向代理服务器之后并且 Django 似乎无法判断请求何时实际上已经安全,则您可能需要设置 [[#id71|:setting:`SECURE_PROXY_SSL_HEADER`]] 设置。
Django can't seem to tell when a request actually is already secure, you
 
may need to set the [[../settings#std-setting-SECURE_PROXY_SSL_HEADER|<code>SECURE_PROXY_SSL_HEADER</code>]] setting.
 
  
  
第448行: 第326行:
  
 
<span id="session-middleware"></span>
 
<span id="session-middleware"></span>
=== Session middleware ===
+
=== 会话中间件 ===
  
; ''class'' <code>SessionMiddleware</code>
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">SessionMiddleware</span></span>
 
:  
 
:  
  
Enables session support. See the [[../../topics/http/sessions|<span class="doc">session documentation</span>]].
+
启用会话支持。 请参阅 [[../../topics/http/sessions|会话文档]]
  
  
第460行: 第338行:
  
 
<span id="site-middleware"></span>
 
<span id="site-middleware"></span>
=== Site middleware ===
+
=== 站点中间件 ===
  
; ''class'' <code>CurrentSiteMiddleware</code>[[../_modules/django/contrib/sites/middleware.html#CurrentSiteMiddleware|<span class="viewcode-link">[源代码]</span>]]
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">CurrentSiteMiddleware</span></span>
 
:  
 
:  
  
Adds the <code>site</code> attribute representing the current site to every incoming
+
将表示当前站点的 <code>site</code> 属性添加到每个传入的 <code>HttpRequest</code> 对象。 请参阅 [[../contrib/sites#site-middleware|站点文档]]
<code>HttpRequest</code> object. See the [[../contrib/sites#site-middleware|<span class="std std-ref">sites documentation</span>]].
 
  
  
第473行: 第350行:
  
 
<span id="authentication-middleware"></span>
 
<span id="authentication-middleware"></span>
=== Authentication middleware ===
+
=== 认证中间件 ===
  
; ''class'' <code>AuthenticationMiddleware</code>
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">AuthenticationMiddleware</span></span>
 
:  
 
:  
  
Adds the <code>user</code> attribute, representing the currently-logged-in user, to
+
向每个传入的 <code>HttpRequest</code> 对象添加表示当前登录用户的 <code>user</code> 属性。 请参阅 [[../../topics/auth/default#auth-web-requests|Web 请求中的身份验证]]
every incoming <code>HttpRequest</code> object. See [[../../topics/auth/default#auth-web-requests|<span class="std std-ref">Authentication in Web requests</span>]].
 
  
; ''class'' <code>RemoteUserMiddleware</code>
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">RemoteUserMiddleware</span></span>
 
:  
 
:  
  
Middleware for utilizing Web server provided authentication. See
+
用于利用 Web 服务器提供的身份验证的中间件。 有关使用详细信息,请参阅 [[../../howto/auth-remote-user|使用 REMOTE_USER]] 进行身份验证。
[[../../howto/auth-remote-user|<span class="doc">使用 REMOTE_USER 进行身份验证</span>]] for usage details.
 
  
; ''class'' <code>PersistentRemoteUserMiddleware</code>
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">PersistentRemoteUserMiddleware</span></span>
 
:  
 
:  
  
Middleware for utilizing Web server provided authentication when enabled only
+
仅在登录页面上启用时,用于利用 Web 服务器提供的身份验证的中间件。 有关使用详细信息,请参阅 [[../../howto/auth-remote-user#persistent-remote-user-middleware-howto|仅在登录页面上使用 REMOTE_USER]]
on the login page. See [[../../howto/auth-remote-user#persistent-remote-user-middleware-howto|<span class="std std-ref">仅在登录界面使用 REMOTE_USER</span>]] for usage
 
details.
 
  
  
第498行: 第371行:
 
<div id="csrf-protection-middleware" class="section">
 
<div id="csrf-protection-middleware" class="section">
  
=== CSRF protection middleware ===
+
=== CSRF 保护中间件 ===
  
; ''class'' <code>CsrfViewMiddleware</code>
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">CsrfViewMiddleware</span></span>
 
:  
 
:  
  
Adds protection against Cross Site Request Forgeries by adding hidden form
+
通过向 POST 表单添加隐藏表单字段并检查请求的正确值来增加对跨站点请求伪造的保护。 请参阅 [[../csrf|跨站点请求伪造保护文档]]
fields to POST forms and checking requests for the correct value. See the
 
[[../csrf|<span class="doc">Cross Site Request Forgery protection documentation</span>]].
 
  
  
第511行: 第382行:
 
<div id="x-frame-options-middleware" class="section">
 
<div id="x-frame-options-middleware" class="section">
  
=== <code>X-Frame-Options</code> middleware ===
+
=== X-Frame-Options 中间件 ===
  
; ''class'' <code>XFrameOptionsMiddleware</code>[[../_modules/django/middleware/clickjacking.html#XFrameOptionsMiddleware|<span class="viewcode-link">[源代码]</span>]]
+
; ''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">XFrameOptionsMiddleware</span></span>
 
:  
 
:  
  
Simple [[../clickjacking|<span class="doc">clickjacking protection via the X-Frame-Options header</span>]].
+
通过 X-Frame-Options 标头 [[../clickjacking|进行简单的]] 点击劫持保护。
  
  
第524行: 第395行:
 
<div id="middleware-ordering" class="section">
 
<div id="middleware-ordering" class="section">
  
<span id="id11"></span>
+
<span id="id73"></span>
== Middleware ordering ==
+
== 中间件订购 ==
  
Here are some hints about the ordering of various Django middleware classes:
+
以下是有关各种 Django 中间件类的排序的一些提示:
  
 
<ol>
 
<ol>
 
<li><p>[[#django.middleware.security.SecurityMiddleware|<code>SecurityMiddleware</code>]]</p>
 
<li><p>[[#django.middleware.security.SecurityMiddleware|<code>SecurityMiddleware</code>]]</p>
<p>It should go near the top of the list if you're going to turn on the SSL
+
<p>如果您要打开 SSL 重定向,它应该靠近列表的顶部,因为这样可以避免运行一堆其他不必要的中间件。</p></li>
redirect as that avoids running through a bunch of other unnecessary
 
middleware.</p></li>
 
 
<li><p>[[#django.middleware.cache.UpdateCacheMiddleware|<code>UpdateCacheMiddleware</code>]]</p>
 
<li><p>[[#django.middleware.cache.UpdateCacheMiddleware|<code>UpdateCacheMiddleware</code>]]</p>
<p>Before those that modify the <code>Vary</code> header (<code>SessionMiddleware</code>,
+
<p>在修改 <code>Vary</code> 头文件之前(<code>SessionMiddleware</code><code>GZipMiddleware</code><code>LocaleMiddleware</code>)。</p></li>
<code>GZipMiddleware</code>, <code>LocaleMiddleware</code>).</p></li>
 
 
<li><p>[[#django.middleware.gzip.GZipMiddleware|<code>GZipMiddleware</code>]]</p>
 
<li><p>[[#django.middleware.gzip.GZipMiddleware|<code>GZipMiddleware</code>]]</p>
<p>Before any middleware that may change or use the response body.</p>
+
<p>在任何可能更改或使用响应正文的中间件之前。</p>
<p>After <code>UpdateCacheMiddleware</code>: Modifies <code>Vary</code> header.</p></li>
+
<p><code>UpdateCacheMiddleware</code> 后:修改 <code>Vary</code> 标题。</p></li>
 
<li><p>[[#django.contrib.sessions.middleware.SessionMiddleware|<code>SessionMiddleware</code>]]</p>
 
<li><p>[[#django.contrib.sessions.middleware.SessionMiddleware|<code>SessionMiddleware</code>]]</p>
<p>Before any middleware that may raise an an exception to trigger an error
+
<p>如果您使用 [[#id74|:setting:`CSRF_USE_SESSIONS`]],则在任何可能引发异常以触发错误视图(例如 [[../exceptions#django.core.exceptions|PermissionDenied]])的中间件之前。</p>
view (such as [[../exceptions#django.core.exceptions|<code>PermissionDenied</code>]]) if you're
+
<p><code>UpdateCacheMiddleware</code> 后:修改 <code>Vary</code> 标题。</p></li>
using [[../settings#std-setting-CSRF_USE_SESSIONS|<code>CSRF_USE_SESSIONS</code>]].</p>
 
<p>After <code>UpdateCacheMiddleware</code>: Modifies <code>Vary</code> header.</p></li>
 
 
<li><p>[[#django.middleware.http.ConditionalGetMiddleware|<code>ConditionalGetMiddleware</code>]]</p>
 
<li><p>[[#django.middleware.http.ConditionalGetMiddleware|<code>ConditionalGetMiddleware</code>]]</p>
<p>Before any middleware that may change the response (it sets the <code>ETag</code>
+
<p>在任何可能更改响应的中间件之前(它设置 <code>ETag</code> 标头)。</p>
header).</p>
+
<p><code>GZipMiddleware</code> 之后,它不会计算 gzipped 内容的 <code>ETag</code> 标头。</p></li>
<p>After <code>GZipMiddleware</code> so it won't calculate an <code>ETag</code> header on gzipped
 
contents.</p></li>
 
 
<li><p>[[#django.middleware.locale.LocaleMiddleware|<code>LocaleMiddleware</code>]]</p>
 
<li><p>[[#django.middleware.locale.LocaleMiddleware|<code>LocaleMiddleware</code>]]</p>
<p>One of the topmost, after <code>SessionMiddleware</code> (uses session data) and
+
<p>最顶层之一,在 <code>SessionMiddleware</code>(使用会话数据)和 <code>UpdateCacheMiddleware</code>(修改 <code>Vary</code> 标头)之后。</p></li>
<code>UpdateCacheMiddleware</code> (modifies <code>Vary</code> header).</p></li>
 
 
<li><p>[[#django.middleware.common.CommonMiddleware|<code>CommonMiddleware</code>]]</p>
 
<li><p>[[#django.middleware.common.CommonMiddleware|<code>CommonMiddleware</code>]]</p>
<p>Before any middleware that may change the response (it sets the
+
<p>在任何可能更改响应的中间件之前(它设置 <code>Content-Length</code> 标头)。 出现在 <code>CommonMiddleware</code> 之前并更改响应的中间件必须重置 <code>Content-Length</code></p>
<code>Content-Length</code> header). A middleware that appears before
+
<p>靠近顶部:当 [[#id76|:setting:`APPEND_SLASH`]] [[#id78|:setting:`PREPEND_WWW`]] 设置为 <code>True</code> 时重定向。</p>
<code>CommonMiddleware</code> and changes the response must reset <code>Content-Length</code>.</p>
+
<p><code>SessionMiddleware</code> 之后,如果您使用 [[#id80|:setting:`CSRF_USE_SESSIONS`]]</p></li>
<p>Close to the top: it redirects when [[../settings#std-setting-APPEND_SLASH|<code>APPEND_SLASH</code>]] or
 
[[../settings#std-setting-PREPEND_WWW|<code>PREPEND_WWW</code>]] are set to <code>True</code>.</p>
 
<p>After <code>SessionMiddleware</code> if you're using [[../settings#std-setting-CSRF_USE_SESSIONS|<code>CSRF_USE_SESSIONS</code>]].</p></li>
 
 
<li><p>[[#django.middleware.csrf.CsrfViewMiddleware|<code>CsrfViewMiddleware</code>]]</p>
 
<li><p>[[#django.middleware.csrf.CsrfViewMiddleware|<code>CsrfViewMiddleware</code>]]</p>
<p>Before any view middleware that assumes that CSRF attacks have been dealt
+
<p>在任何假设 CSRF 攻击已被处理的视图中间件之前。</p>
with.</p>
+
<p>[[#django.contrib.auth.middleware.RemoteUserMiddleware|RemoteUserMiddleware]] 或任何其他可能执行登录并因此轮换 CSRF 令牌的身份验证中间件之前,在调用中间件链之前。</p>
<p>Before [[#django.contrib.auth.middleware.RemoteUserMiddleware|<code>RemoteUserMiddleware</code>]], or any
+
<p><code>SessionMiddleware</code> 之后,如果您使用 [[#id82|:setting:`CSRF_USE_SESSIONS`]]</p></li>
other authentication middleware that may perform a login, and hence rotate
 
the CSRF token, before calling down the middleware chain.</p>
 
<p>After <code>SessionMiddleware</code> if you're using [[../settings#std-setting-CSRF_USE_SESSIONS|<code>CSRF_USE_SESSIONS</code>]].</p></li>
 
 
<li><p>[[#django.contrib.auth.middleware.AuthenticationMiddleware|<code>AuthenticationMiddleware</code>]]</p>
 
<li><p>[[#django.contrib.auth.middleware.AuthenticationMiddleware|<code>AuthenticationMiddleware</code>]]</p>
<p>After <code>SessionMiddleware</code>: uses session storage.</p></li>
+
<p><code>SessionMiddleware</code> 之后:使用会话存储。</p></li>
 
<li><p>[[#django.contrib.messages.middleware.MessageMiddleware|<code>MessageMiddleware</code>]]</p>
 
<li><p>[[#django.contrib.messages.middleware.MessageMiddleware|<code>MessageMiddleware</code>]]</p>
<p>After <code>SessionMiddleware</code>: can use session-based storage.</p></li>
+
<p><code>SessionMiddleware</code>之后:可以使用基于会话的存储。</p></li>
 
<li><p>[[#django.middleware.cache.FetchFromCacheMiddleware|<code>FetchFromCacheMiddleware</code>]]</p>
 
<li><p>[[#django.middleware.cache.FetchFromCacheMiddleware|<code>FetchFromCacheMiddleware</code>]]</p>
<p>After any middleware that modifies the <code>Vary</code> header: that header is used
+
<p>在修改 <code>Vary</code> 标头的任何中间件之后:该标头用于为缓存哈希键选择一个值。</p></li>
to pick a value for the cache hash-key.</p></li>
 
 
<li><p>[[../contrib/flatpages#django.contrib.flatpages.middleware|<code>FlatpageFallbackMiddleware</code>]]</p>
 
<li><p>[[../contrib/flatpages#django.contrib.flatpages.middleware|<code>FlatpageFallbackMiddleware</code>]]</p>
<p>Should be near the bottom as it's a last-resort type of middleware.</p></li>
+
<p>应该靠近底部,因为它是最后的中间件类型。</p></li>
 
<li><p>[[../contrib/redirects#django.contrib.redirects.middleware|<code>RedirectFallbackMiddleware</code>]]</p>
 
<li><p>[[../contrib/redirects#django.contrib.redirects.middleware|<code>RedirectFallbackMiddleware</code>]]</p>
<p>Should be near the bottom as it's a last-resort type of middleware.</p></li></ol>
+
<p>应该靠近底部,因为它是最后的中间件类型。</p></li></ol>
  
  
第583行: 第439行:
  
 
</div>
 
</div>
 +
<div class="clearer">
  
[[Category:Django 3.0.x 中文文档]]
+
 
 +
 
 +
</div>
 +
 
 +
[[Category:Django 3.0.x 文档]]

2021年10月31日 (日) 04:09的最新版本

中间件

本文档解释了 Django 附带的所有中间件组件。 有关如何使用它们以及如何编写自己的中间件的信息,请参阅 中间件使用指南

可用的中间件

缓存中间件

class UpdateCacheMiddleware
class FetchFromCacheMiddleware

启用站点范围的缓存。 如果启用这些,每个 Django 驱动的页面将被缓存,只要 :setting:`CACHE_MIDDLEWARE_SECONDS` 设置定义。 请参阅 缓存文档


“通用”中间件

class CommonMiddleware

为完美主义者增加了一些便利:

  • 禁止访问 :setting:`DISALLOWED_USER_AGENTS` 设置中的用户代理,该设置应该是已编译的正则表达式对象列表。

  • 根据 :setting:`APPEND_SLASH`:setting:`PREPEND_WWW` 设置执行 URL 重写。

    如果 :setting:`APPEND_SLASH`True 并且初始 URL 不以斜杠结尾,并且在 URLconf 中找不到,则通过附加一个新 URL 形成斜线在最后。 如果在 URLconf 中找到了这个新 URL,那么 Django 会将请求重定向到这个新 URL。 否则,将照常处理初始 URL。

    例如,如果 foo.com/bar 没有有效的 URL 模式,但 do 有 的有效模式,则 foo.com/bar 将被重定向到 foo.com/bar/ X148X]。

    如果 :setting:`PREPEND_WWW`True,则缺少前导“www”的 URL。 将被重定向到以“www”开头的相同 URL。

    这两个选项都用于规范化 URL。 其理念是每个 URL 都应存在于一个且仅一个位置。 从技术上讲,URL foo.com/barfoo.com/bar/ 不同——搜索引擎索引器会将它们视为单独的 URL——因此最佳做法是规范化 URL。

  • 为非流响应设置 Content-Length 标头。

CommonMiddleware.response_redirect_class

默认为 HttpResponsePermanentRedirect。 子类 CommonMiddleware 并覆盖该属性以自定义中间件发出的重定向。

class BrokenLinkEmailsMiddleware


GZip中间件

class GZipMiddleware

警告

安全研究人员最近透露,当在网站上使用压缩技术(包括 GZipMiddleware)时,该网站可能会受到多种可能的攻击。 在您的站点上使用 GZipMiddleware 之前,您应该非常仔细地考虑您是否受到这些攻击。 如果你在 任何 怀疑你是否受到影响,你应该避免使用 GZipMiddleware。 有关更多详细信息,请参阅 the BREACH 论文 (PDF)breachattack.com


django.middleware.gzip.GZipMiddleware 为理解 GZip 压缩的浏览器(所有现代浏览器)压缩内容。

该中间件应放置在需要读取或写入响应正文的任何其他中间件之前,以便随后进行压缩。

如果以下任何一项为真,它将不会压缩内容:

  • 内容主体长度小于 200 字节。
  • 响应已经设置了 Content-Encoding 标头。
  • 请求(浏览器)尚未发送包含 gzipAccept-Encoding 标头。

如果响应具有 ETag 标头,则 ETag 会变弱以符合 RFC 7232#section-2.1

您可以使用 gzip_page() 装饰器将 GZip 压缩应用于单个视图。


条件获取中间件

class ConditionalGetMiddleware

处理条件 GET 操作。 如果响应没有 ETag 标头,中间件会根据需要添加一个。 如果响应具有 ETagLast-Modified 标头,并且请求具有 If-None-MatchIf-Modified-Since,则响应被替换为 HttpResponseNotModified ]。


语言环境中间件

class LocaleMiddleware

根据请求中的数据启用语言选择。 它为每个用户定制内容。 请参阅 国际化文档

LocaleMiddleware.response_redirect_class

默认为 HttpResponseRedirect。 子类 LocaleMiddleware 并覆盖该属性以自定义中间件发出的重定向。


消息中间件

class MessageMiddleware

启用基于 cookie 和会话的消息支持。 请参阅 消息文档


安全中间件

警告

如果您的部署情况允许,让您的前端 Web 服务器执行 SecurityMiddleware 提供的功能通常是个好主意。 这样,如果有 Django 不提供的请求(例如静态媒体或用户上传的文件),它们将具有与对 Django 应用程序的请求相同的保护。


class SecurityMiddleware

django.middleware.security.SecurityMiddleware 为请求/响应周期提供了多项安全增强功能。 每个都可以通过设置独立启用或禁用。

HTTP 严格传输安全

对于只能通过 HTTPS 访问的站点,您可以通过设置 “Strict-Transport-Security” 标头 “Strict-Transport-Security” 标头,指示现代浏览器拒绝通过不安全连接(在给定时间段内)连接到您的域名X234X]。 这减少了您遭受某些 SSL 剥离中间人 (MITM) 攻击的风险。

如果您将 :setting:`SECURE_HSTS_SECONDS` 设置为非零整数值,SecurityMiddleware 将在所有 HTTPS 响应中为您设置此标头。

启用 HSTS 时,最好先使用较小的值进行测试,例如, :设置:`SECURE_HSTS_SECONDS = 3600 ` 一小时。 每次 Web 浏览器从您的站点看到 HSTS 标头时,它都会在给定的时间段内拒绝与您的域进行非安全(使用 HTTP)通信。 一旦您确认所有资产都在您的网站上安全地提供(即 HSTS 没有破坏任何东西),增加这个值是个好主意,这样不频繁的访问者将受到保护(31536000 秒,即 1 年,很常见)。

此外,如果您将 :setting:`SECURE_HSTS_INCLUDE_SUBDOMAINS` 设置为 TrueSecurityMiddleware 会将 includeSubDomains 指令添加到 [X15] ] 标题。 这是推荐的(假设所有子域都只使用 HTTPS 提供服务),否则您的站点可能仍然容易通过与子域的不安全连接而受到攻击。

如果您希望将您的站点提交到 浏览器预加载列表 ,请将 :setting:`SECURE_HSTS_PRELOAD` 设置为 True。 将 preload 指令附加到 Strict-Transport-Security 标头。

警告

HSTS 策略适用于您的整个域,而不仅仅是您设置标头的响应的 URL。 因此,仅当您的整个域仅通过 HTTPS 提供服务时才应使用它。

正确遵守 HSTS 标头的浏览器将拒绝允许用户绕过警告并连接到具有过期、自签名或其他无效 SSL 证书的站点。 如果您使用 HSTS,请确保您的证书状态良好并保持这种状态!


笔记

如果您部署在负载平衡器或反向代理服务器之后,并且 Strict-Transport-Security 标头未添加到您的响应中,则可能是因为 Django 没有意识到它处于安全连接上; 您可能需要设置 :setting:`SECURE_PROXY_SSL_HEADER` 设置。


推荐人政策

3.0 版中的新功能。


浏览器使用 引用标头 作为向站点发送有关用户如何到达那里的信息的一种方式。 当用户单击链接时,浏览器将发送链接页面的完整 URL 作为引用者。 虽然这对某些目的很有用——比如找出谁链接到你的网站——但它也可能会通过通知一个网站用户正在访问另一个网站而引起隐私问题。

某些浏览器能够接受有关在用户单击链接时是否应该发送 HTTP Referer 标头的提示; 此提示是通过 引用策略标头 提供的。 此标头可以向浏览器建议以下三种行为中的任何一种:

此标头可以告诉浏览器注意两种类型的条件:

警告

当您的站点通过 HTTPS 提供服务时,Django 的 CSRF 保护系统 要求存在 Referer 标头,因此完全禁用 Referer 标头会干扰 CSRF 保护。 要获得禁用 Referer 标头的大部分好处,同时保持 CSRF 保护,请考虑仅启用同源引用。


SecurityMiddleware 可以根据 :setting:`SECURE_REFERRER_POLICY` 设置为您设置 Referrer-Policy 标头(注意拼写:浏览器发送 Referer 标头当用户单击链接,但指示浏览器是否这样做的标题拼写为 Referrer-Policy)。 此设置的有效值为:

no-referrer
指示浏览器不为在此站点上单击的链接发送引荐来源网址。
no-referrer-when-downgrade
指示浏览器发送完整的 URL 作为引用者,但仅当没有发生协议降级时。
origin
指示浏览器仅发送来源,而不是完整的 URL,作为引用者。
origin-when-cross-origin
指示浏览器发送完整的 URL 作为同源链接的引用来源,并且只发送跨源链接的来源。
same-origin
指示浏览器发送完整的 URL,但仅用于同源链接。 不会为跨源链接发送推荐人。
strict-origin
指示浏览器仅发送源,而不是完整的 URL,并且在发生协议降级时不发送引用。
strict-origin-when-cross-origin
当链接是同源的并且没有发生协议降级时,指示浏览器发送完整的URL; 当链路是跨域的并且没有发生协议降级时,只发送源; 并且在发生协议降级时没有引用者。
unsafe-url
指示浏览器始终将完整 URL 作为引用者发送。

未知的策略值

如果用户代理的策略值为 unknown,则可以指定多个策略值以提供回退。 最后一个被理解的指定值优先。 为了支持这一点,可以将可迭代或逗号分隔的字符串与 :setting:`SECURE_REFERRER_POLICY` 一起使用。


X-Content-Type-Options: nosniff

一些浏览器会尝试猜测它们获取的资产的内容类型,覆盖 Content-Type 标头。 虽然这有助于显示服务器配置不当的站点,但它也可能带来安全风险。

如果您的站点提供用户上传的文件,恶意用户可能会上传一个特制的文件,当您认为它是无害的时,浏览器会将其解释为 HTML 或 JavaScript。

为了防止浏览器猜测内容类型并强制它始终使用 Content-Type 标头中提供的类型,您可以传递 X-Content-Type-Options: nosniff 标头。 SecurityMiddleware 将对所有响应执行此操作,如果 :setting:`SECURE_CONTENT_TYPE_NOSNIFF` 设置为 True

请注意,在 Django 不参与为用户上传的文件提供服务的大多数部署情况下,此设置对您没有帮助。 例如,如果您的 :setting:`MEDIA_URL` 直接由您的前端 Web 服务器(nginx、Apache 等)提供服务,那么您需要在那里设置此标头。 另一方面,如果您使用 Django 执行诸如需要授权才能下载文件之类的操作,并且您无法使用 Web 服务器设置标头,则此设置将很有用。


X-XSS-Protection: 1; mode=block

某些浏览器能够阻止看起来像是 XSS 攻击 的内容。 它们通过在页面的 GET 或 POST 参数中查找 JavaScript 内容来工作。 如果 JavaScript 在服务器的响应中被重播,页面将被阻止呈现并显示错误页面。

X-XSS-Protection头用于控制XSS过滤器的操作。

要在浏览器中启用 XSS 过滤器,并强制它始终阻止可疑的 XSS 攻击,您可以传递 X-XSS-Protection: 1; mode=block 标头。 如果 :setting:`SECURE_BROWSER_XSS_FILTER` 设置为 TrueSecurityMiddleware 将对所有响应执行此操作。

警告

浏览器 XSS 过滤器是一种有用的防御措施,但不能完全依赖。 它不能检测所有 XSS 攻击,也不是所有浏览器都支持标头。 确保您仍在 验证和清理 所有输入以防止 XSS 攻击。


SSL 重定向

如果您的站点同时提供 HTTP 和 HTTPS 连接,默认情况下大多数用户最终会使用不安全的连接。 为了获得最佳安全性,您应该将所有 HTTP 连接重定向到 HTTPS。

如果您将 :setting:`SECURE_SSL_REDIRECT` 设置为 True,SecurityMiddleware 将永久 (HTTP 301) 将所有 HTTP 连接重定向到 HTTPS。

笔记

出于性能原因,最好在 Django 之外、在前端负载平衡器或反向代理服务器(如 nginx)中进行这些重定向。 :setting:`SECURE_SSL_REDIRECT` 适用于无法选择的部署情况。


如果 :setting:`SECURE_SSL_HOST` 设置具有值,则所有重定向都将发送到该主机而不是最初请求的主机。

如果您的站点上有几个页面应该可以通过 HTTP 访问,而不是重定向到 HTTPS,您可以在 :setting:`SECURE_REDIRECT_EXEMPT` 设置中列出与这些 URL 匹配的正则表达式。

笔记

如果您部署在负载均衡器或反向代理服务器之后并且 Django 似乎无法判断请求何时实际上已经安全,则您可能需要设置 :setting:`SECURE_PROXY_SSL_HEADER` 设置。


会话中间件

class SessionMiddleware

启用会话支持。 请参阅 会话文档


站点中间件

class CurrentSiteMiddleware

将表示当前站点的 site 属性添加到每个传入的 HttpRequest 对象。 请参阅 站点文档


认证中间件

class AuthenticationMiddleware

向每个传入的 HttpRequest 对象添加表示当前登录用户的 user 属性。 请参阅 Web 请求中的身份验证

class RemoteUserMiddleware

用于利用 Web 服务器提供的身份验证的中间件。 有关使用详细信息,请参阅 使用 REMOTE_USER 进行身份验证。

class PersistentRemoteUserMiddleware

仅在登录页面上启用时,用于利用 Web 服务器提供的身份验证的中间件。 有关使用详细信息,请参阅 仅在登录页面上使用 REMOTE_USER


CSRF 保护中间件

class CsrfViewMiddleware

通过向 POST 表单添加隐藏表单字段并检查请求的正确值来增加对跨站点请求伪造的保护。 请参阅 跨站点请求伪造保护文档


X-Frame-Options 中间件

class XFrameOptionsMiddleware

通过 X-Frame-Options 标头 进行简单的 点击劫持保护。


中间件订购

以下是有关各种 Django 中间件类的排序的一些提示:

  1. SecurityMiddleware

    如果您要打开 SSL 重定向,它应该靠近列表的顶部,因为这样可以避免运行一堆其他不必要的中间件。

  2. UpdateCacheMiddleware

    在修改 Vary 头文件之前(SessionMiddlewareGZipMiddlewareLocaleMiddleware)。

  3. GZipMiddleware

    在任何可能更改或使用响应正文的中间件之前。

    UpdateCacheMiddleware 后:修改 Vary 标题。

  4. SessionMiddleware

    如果您使用 :setting:`CSRF_USE_SESSIONS`,则在任何可能引发异常以触发错误视图(例如 PermissionDenied)的中间件之前。

    UpdateCacheMiddleware 后:修改 Vary 标题。

  5. ConditionalGetMiddleware

    在任何可能更改响应的中间件之前(它设置 ETag 标头)。

    GZipMiddleware 之后,它不会计算 gzipped 内容的 ETag 标头。

  6. LocaleMiddleware

    最顶层之一,在 SessionMiddleware(使用会话数据)和 UpdateCacheMiddleware(修改 Vary 标头)之后。

  7. CommonMiddleware

    在任何可能更改响应的中间件之前(它设置 Content-Length 标头)。 出现在 CommonMiddleware 之前并更改响应的中间件必须重置 Content-Length

    靠近顶部:当 :setting:`APPEND_SLASH`:setting:`PREPEND_WWW` 设置为 True 时重定向。

    SessionMiddleware 之后,如果您使用 :setting:`CSRF_USE_SESSIONS`

  8. CsrfViewMiddleware

    在任何假设 CSRF 攻击已被处理的视图中间件之前。

    RemoteUserMiddleware 或任何其他可能执行登录并因此轮换 CSRF 令牌的身份验证中间件之前,在调用中间件链之前。

    SessionMiddleware 之后,如果您使用 :setting:`CSRF_USE_SESSIONS`

  9. AuthenticationMiddleware

    SessionMiddleware 之后:使用会话存储。

  10. MessageMiddleware

    SessionMiddleware之后:可以使用基于会话的存储。

  11. FetchFromCacheMiddleware

    在修改 Vary 标头的任何中间件之后:该标头用于为缓存哈希键选择一个值。

  12. FlatpageFallbackMiddleware

    应该靠近底部,因为它是最后的中间件类型。

  13. RedirectFallbackMiddleware

    应该靠近底部,因为它是最后的中间件类型。