{"title":"中间件","version":"4.0","locale":"zh-hans","docname":"ref/middleware","url":"/zh-hans/4.0/ref/middleware/","canonical":"https://djangodocs.dev/zh-hans/4.0/ref/middleware/","summary":"这篇文档解释了所有 Django 自带的中间件组件。关于如何使用它们以及如何编写自己的中间件，请参见中间件使用指南。","html":"<span id=\"middleware\"></span><h1>中间件<a class=\"heading-anchor\" href=\"#module-django.middleware\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h1>\n<p>这篇文档解释了所有 Django 自带的中间件组件。关于如何使用它们以及如何编写自己的中间件，请参见 <a class=\"reference internal\" href=\"/zh-hans/4.0/topics/http/middleware/\"><span class=\"doc\">中间件使用指南</span></a>。</p>\n<section id=\"available-middleware\">\n<h2>可用的中间件<a class=\"heading-anchor\" href=\"#available-middleware\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<section id=\"module-django.middleware.cache\">\n<span id=\"cache-middleware\"></span><h3>缓存中间件<a class=\"heading-anchor\" href=\"#module-django.middleware.cache\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<dl class=\"py class\">\n<dt class=\"sig sig-object py\" id=\"django.middleware.cache.UpdateCacheMiddleware\">\n<em class=\"property\"><span class=\"k\">class</span> </em><span class=\"sig-name descname\">UpdateCacheMiddleware</span><a class=\"heading-anchor\" href=\"#django.middleware.cache.UpdateCacheMiddleware\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<dl class=\"py class\">\n<dt class=\"sig sig-object py\" id=\"django.middleware.cache.FetchFromCacheMiddleware\">\n<em class=\"property\"><span class=\"k\">class</span> </em><span class=\"sig-name descname\">FetchFromCacheMiddleware</span><a class=\"heading-anchor\" href=\"#django.middleware.cache.FetchFromCacheMiddleware\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>启用全站缓存。如果启用了这些功能，那么每一个 Django 驱动的页面都会在 <a class=\"reference internal\" href=\"/zh-hans/4.0/ref/settings/#std-setting-CACHE_MIDDLEWARE_SECONDS\"><code class=\"xref std std-setting docutils literal notranslate\">CACHE_MIDDLEWARE_SECONDS</code></a> 配置定义的时间内被缓存。参见 <a class=\"reference internal\" href=\"/zh-hans/4.0/topics/cache/\"><span class=\"doc\">缓存文档</span></a>。</p>\n</section>\n<section id=\"module-django.middleware.common\">\n<span id=\"common-middleware\"></span><h3>“通用”中间件<a class=\"heading-anchor\" href=\"#module-django.middleware.common\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<dl class=\"py class\">\n<dt class=\"sig sig-object py\" id=\"django.middleware.common.CommonMiddleware\">\n<em class=\"property\"><span class=\"k\">class</span> </em><span class=\"sig-name descname\">CommonMiddleware</span><a class=\"heading-anchor\" href=\"#django.middleware.common.CommonMiddleware\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>为完美主义者增加了一些便利：</p>\n<ul>\n<li><p>禁止 <a class=\"reference internal\" href=\"/zh-hans/4.0/ref/settings/#std-setting-DISALLOWED_USER_AGENTS\"><code class=\"xref std std-setting docutils literal notranslate\">DISALLOWED_USER_AGENTS</code></a> 配置中的用户代理访问，它应该是一个编译的正则表达式对象列表。</p></li>\n<li><p>根据 <a class=\"reference internal\" href=\"/zh-hans/4.0/ref/settings/#std-setting-APPEND_SLASH\"><code class=\"xref std std-setting docutils literal notranslate\">APPEND_SLASH</code></a> 和 <a class=\"reference internal\" href=\"/zh-hans/4.0/ref/settings/#std-setting-PREPEND_WWW\"><code class=\"xref std std-setting docutils literal notranslate\">PREPEND_WWW</code></a> 的配置进行 URL 重写。</p>\n<p>如果 <a class=\"reference internal\" href=\"/zh-hans/4.0/ref/settings/#std-setting-APPEND_SLASH\"><code class=\"xref std std-setting docutils literal notranslate\">APPEND_SLASH</code></a> 为 <code class=\"docutils literal notranslate\">True</code>，并且初始的 URL 没有以斜线结尾，而且在 URLconf 中也没有找到，那么就会在最后附加一个斜线形成一个新的 URL。如果在 URLconf 中找到了这个新的 URL，那么 Django 会将请求重定向到这个新的 URL。否则，初始的 URL 就会被照常处理。</p>\n<p>例如，<code class=\"docutils literal notranslate\">foo.com/bar</code> 将被重定向到 <code class=\"docutils literal notranslate\">foo.com/bar/</code>，如果你没有 <code class=\"docutils literal notranslate\">foo.com/bar</code> 的有效 URL 模式，但 <em>有</em> <code class=\"docutils literal notranslate\">foo.com/bar/</code> 的有效模式。</p>\n<p>如果 <a class=\"reference internal\" href=\"/zh-hans/4.0/ref/settings/#std-setting-PREPEND_WWW\"><code class=\"xref std std-setting docutils literal notranslate\">PREPEND_WWW</code></a> 为 <code class=\"docutils literal notranslate\">True</code>，缺乏前导“www. ”的 URL 将被重定向到带有前导“www. ”的同一 URL。</p>\n<p>这两个选项都是为了规范 URL。其理念是，每个 URL 应该存在于一个地方，而且只有一个地方。从技术上讲，URL <code class=\"docutils literal notranslate\">foo.com/bar</code> 与 <code class=\"docutils literal notranslate\">foo.com/bar/</code> 是不同的——搜索引擎索引器会将它们视为单独的 URL——所以最好的做法是将 URL 规范化。</p>\n<p>如果有必要，可以使用 <a class=\"reference internal\" href=\"/zh-hans/4.0/topics/http/decorators/#django.views.decorators.common.no_append_slash\" title=\"django.views.decorators.common.no_append_slash\"><code class=\"xref py py-func docutils literal notranslate\">no_append_slash()</code></a> 装饰器将个别视图从 <code class=\"docutils literal notranslate\">APPEND_SLASH</code> 行为中排除：</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.views.decorators.common</span> <span class=\"kn\">import</span> no_append_slash\n\n<span class=\"nd\">@no_append_slash</span>\n<span class=\"k\">def</span> <span class=\"nf\">sensitive_fbv</span><span class=\"p\">(</span>request<span class=\"p\">,</span> <span class=\"o\">*</span>args<span class=\"p\">,</span> <span class=\"o\">**</span>kwargs<span class=\"p\">):</span>\n    <span class=\"sd\">&quot;&quot;&quot;View to be excluded from APPEND_SLASH.&quot;&quot;&quot;</span>\n    <span class=\"k\">return</span> HttpResponse<span class=\"p\">()</span>\n</code></pre></div>\n<aside class=\"version-note version-changed\" data-version=\"3.2\" role=\"note\">\n<p class=\"version-note-title\">Changed in Django 3.2</p><p>增加了对 <a class=\"reference internal\" href=\"/zh-hans/4.0/topics/http/decorators/#django.views.decorators.common.no_append_slash\" title=\"django.views.decorators.common.no_append_slash\"><code class=\"xref py py-func docutils literal notranslate\">no_append_slash()</code></a> 装饰器的支持。</p>\n</aside>\n</li>\n<li><p>设置非流响应的 <code class=\"docutils literal notranslate\">Content-Length</code> 头。</p></li>\n</ul>\n<dl class=\"py attribute\">\n<dt class=\"sig sig-object py\" id=\"django.middleware.common.CommonMiddleware.response_redirect_class\">\n<span class=\"sig-prename descclassname\">CommonMiddleware.</span><span class=\"sig-name descname\">response_redirect_class</span><a class=\"heading-anchor\" href=\"#django.middleware.common.CommonMiddleware.response_redirect_class\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>默认为 <a class=\"reference internal\" href=\"/zh-hans/4.0/ref/request-response/#django.http.HttpResponsePermanentRedirect\" title=\"django.http.HttpResponsePermanentRedirect\"><code class=\"xref py py-class docutils literal notranslate\">HttpResponsePermanentRedirect</code></a>。子类化 <code class=\"docutils literal notranslate\">CommonMiddleware</code>，并重写该属性来定制中间件发出的重定向。</p>\n<dl class=\"py class\">\n<dt class=\"sig sig-object py\" id=\"django.middleware.common.BrokenLinkEmailsMiddleware\">\n<em class=\"property\"><span class=\"k\">class</span> </em><span class=\"sig-name descname\">BrokenLinkEmailsMiddleware</span><a class=\"heading-anchor\" href=\"#django.middleware.common.BrokenLinkEmailsMiddleware\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<ul class=\"simple\">\n<li><p>向 <code class=\"xref std std-setting docutils literal notranslate\">manager</code> 发送失效链接通知邮件（参见 <a class=\"reference internal\" href=\"/zh-hans/4.0/howto/error-reporting/\"><span class=\"doc\">如何管理错误报告</span></a>）。</p></li>\n</ul>\n</section>\n<section id=\"module-django.middleware.gzip\">\n<span id=\"gzip-middleware\"></span><h3>GZip 中间件<a class=\"heading-anchor\" href=\"#module-django.middleware.gzip\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<dl class=\"py class\">\n<dt class=\"sig sig-object py\" id=\"django.middleware.gzip.GZipMiddleware\">\n<em class=\"property\"><span class=\"k\">class</span> </em><span class=\"sig-name descname\">GZipMiddleware</span><a class=\"heading-anchor\" href=\"#django.middleware.gzip.GZipMiddleware\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<aside class=\"admonition admonition-warning\" role=\"note\">\n<p class=\"admonition-title\">Warning</p>\n<p>安全研究人员最近发现，当在网站上使用压缩技术（包括 <code class=\"docutils literal notranslate\">GZipMiddleware</code>）时，网站可能会受到一些可能的攻击。在你的网站上使用 <code class=\"docutils literal notranslate\">GZipMiddleware</code> 之前，你应该仔细考虑你是否会受到这些攻击。如果你对你是否受到影响有 <em>任何</em> 怀疑，你应该避免使用 <code class=\"docutils literal notranslate\">GZipMiddleware</code>。更多细节，请看 <a class=\"reference external\" href=\"http://breachattack.com/resources/BREACH%20-%20SSL,%20gone%20in%2030%20seconds.pdf\">the BREACH paper (PDF)</a> 和 <a class=\"reference external\" href=\"http://breachattack.com\">breachattack.com</a> 。</p>\n</aside>\n<p><code class=\"docutils literal notranslate\">django.middleware.gzip.GZipMiddleware</code> 为能理解 GZip 压缩的浏览器（所有现代浏览器）压缩内容。</p>\n<p>这个中间件应该放在任何其他需要读取或写入响应体的中间件之前，这样压缩就会在之后发生。</p>\n<p>如果以下任何一项为真，它将不会压缩内容：</p>\n<ul class=\"simple\">\n<li><p>内容主体长度小于 200 字节。</p></li>\n<li><p>响应已经设置了 <code class=\"docutils literal notranslate\">Content-Encoding</code> 头。</p></li>\n<li><p>请求（浏览器）没有发送包含 <code class=\"docutils literal notranslate\">gzip</code> 的 <code class=\"docutils literal notranslate\">Accept-Encoding</code> 头。</p></li>\n</ul>\n<p>如果响应有 <code class=\"docutils literal notranslate\">ETag</code> 头，则 ETag 会变得很弱，以符合 <span class=\"target\" id=\"index-2\"></span><a class=\"rfc reference external\" href=\"https://datatracker.ietf.org/doc/html/rfc7232.html#section-2.1\"><strong>RFC 7232 Section 2.1</strong></a>。</p>\n<p>你可以使用 <a class=\"reference internal\" href=\"/zh-hans/4.0/topics/http/decorators/#django.views.decorators.gzip.gzip_page\" title=\"django.views.decorators.gzip.gzip_page\"><code class=\"xref py py-func docutils literal notranslate\">gzip_page()</code></a> 装饰器对单个视图应用 GZip 压缩。</p>\n</section>\n<section id=\"module-django.middleware.http\">\n<span id=\"conditional-get-middleware\"></span><h3>条件 GET 中间件<a class=\"heading-anchor\" href=\"#module-django.middleware.http\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<dl class=\"py class\">\n<dt class=\"sig sig-object py\" id=\"django.middleware.http.ConditionalGetMiddleware\">\n<em class=\"property\"><span class=\"k\">class</span> </em><span class=\"sig-name descname\">ConditionalGetMiddleware</span><a class=\"heading-anchor\" href=\"#django.middleware.http.ConditionalGetMiddleware\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>处理有条件的 GET 操作。如果响应没有 <code class=\"docutils literal notranslate\">ETag</code> 头，中间件会根据需要添加一个。如果响应有 <code class=\"docutils literal notranslate\">ETag</code> 或 <code class=\"docutils literal notranslate\">Last-Modified</code> 头，而请求有 <code class=\"docutils literal notranslate\">If-None-Match</code> 或 <code class=\"docutils literal notranslate\">If-Modified-Since</code>，则响应被一个 <a class=\"reference internal\" href=\"/zh-hans/4.0/ref/request-response/#django.http.HttpResponseNotModified\" title=\"django.http.HttpResponseNotModified\"><code class=\"xref py py-class docutils literal notranslate\">HttpResponseNotModified</code></a> 替换。</p>\n</section>\n<section id=\"module-django.middleware.locale\">\n<span id=\"locale-middleware\"></span><h3>本地化中间件<a class=\"heading-anchor\" href=\"#module-django.middleware.locale\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<dl class=\"py class\">\n<dt class=\"sig sig-object py\" id=\"django.middleware.locale.LocaleMiddleware\">\n<em class=\"property\"><span class=\"k\">class</span> </em><span class=\"sig-name descname\">LocaleMiddleware</span><a class=\"heading-anchor\" href=\"#django.middleware.locale.LocaleMiddleware\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>可以根据请求的数据选择语言。它为每个用户定制内容。请参阅 <a class=\"reference internal\" href=\"/zh-hans/4.0/topics/i18n/translation/\"><span class=\"doc\">国际化文档</span></a>。</p>\n<dl class=\"py attribute\">\n<dt class=\"sig sig-object py\" id=\"django.middleware.locale.LocaleMiddleware.response_redirect_class\">\n<span class=\"sig-prename descclassname\">LocaleMiddleware.</span><span class=\"sig-name descname\">response_redirect_class</span><a class=\"heading-anchor\" href=\"#django.middleware.locale.LocaleMiddleware.response_redirect_class\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>默认为 <a class=\"reference internal\" href=\"/zh-hans/4.0/ref/request-response/#django.http.HttpResponseRedirect\" title=\"django.http.HttpResponseRedirect\"><code class=\"xref py py-class docutils literal notranslate\">HttpResponseRedirect</code></a>。子类化 <code class=\"docutils literal notranslate\">LocaleMiddleware</code> 并重写该属性，以自定义中间件发出的重定向。</p>\n</section>\n<section id=\"module-django.contrib.messages.middleware\">\n<span id=\"message-middleware\"></span><h3>消息中间件<a class=\"heading-anchor\" href=\"#module-django.contrib.messages.middleware\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<dl class=\"py class\">\n<dt class=\"sig sig-object py\" id=\"django.contrib.messages.middleware.MessageMiddleware\">\n<em class=\"property\"><span class=\"k\">class</span> </em><span class=\"sig-name descname\">MessageMiddleware</span><a class=\"heading-anchor\" href=\"#django.contrib.messages.middleware.MessageMiddleware\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>启用基于 cookie 和会话的消息支持。参见 <a class=\"reference internal\" href=\"/zh-hans/4.0/ref/contrib/messages/\"><span class=\"doc\">消息文档</span></a>。</p>\n</section>\n<section id=\"module-django.middleware.security\">\n<span id=\"id1\"></span><span id=\"security-middleware\"></span><h3>安全中间件<a class=\"heading-anchor\" href=\"#module-django.middleware.security\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<aside class=\"admonition admonition-warning\" role=\"note\">\n<p class=\"admonition-title\">Warning</p>\n<p>If your deployment situation allows, it's usually a good idea to have your\nfront-end web server perform the functionality provided by the\n<code class=\"docutils literal notranslate\">SecurityMiddleware</code>. That way, if there are requests that aren't served\nby Django (such as static media or user-uploaded files), they will have\nthe same protections as requests to your Django application.</p>\n</aside>\n<dl class=\"py class\">\n<dt class=\"sig sig-object py\" id=\"django.middleware.security.SecurityMiddleware\">\n<em class=\"property\"><span class=\"k\">class</span> </em><span class=\"sig-name descname\">SecurityMiddleware</span><a class=\"heading-anchor\" href=\"#django.middleware.security.SecurityMiddleware\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p><code class=\"docutils literal notranslate\">django.middleware.security.SecurityMiddleware</code> 为请求／响应周期提供了若干安全增强功能。每一项都可以通过设置独立地启用或禁用。</p>\n<ul class=\"simple\">\n<li><p><a class=\"reference internal\" href=\"/zh-hans/4.0/ref/settings/#std-setting-SECURE_CONTENT_TYPE_NOSNIFF\"><code class=\"xref std std-setting docutils literal notranslate\">SECURE_CONTENT_TYPE_NOSNIFF</code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/zh-hans/4.0/ref/settings/#std-setting-SECURE_CROSS_ORIGIN_OPENER_POLICY\"><code class=\"xref std std-setting docutils literal notranslate\">SECURE_CROSS_ORIGIN_OPENER_POLICY</code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/zh-hans/4.0/ref/settings/#std-setting-SECURE_HSTS_INCLUDE_SUBDOMAINS\"><code class=\"xref std std-setting docutils literal notranslate\">SECURE_HSTS_INCLUDE_SUBDOMAINS</code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/zh-hans/4.0/ref/settings/#std-setting-SECURE_HSTS_PRELOAD\"><code class=\"xref std std-setting docutils literal notranslate\">SECURE_HSTS_PRELOAD</code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/zh-hans/4.0/ref/settings/#std-setting-SECURE_HSTS_SECONDS\"><code class=\"xref std std-setting docutils literal notranslate\">SECURE_HSTS_SECONDS</code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/zh-hans/4.0/ref/settings/#std-setting-SECURE_REDIRECT_EXEMPT\"><code class=\"xref std std-setting docutils literal notranslate\">SECURE_REDIRECT_EXEMPT</code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/zh-hans/4.0/ref/settings/#std-setting-SECURE_REFERRER_POLICY\"><code class=\"xref std std-setting docutils literal notranslate\">SECURE_REFERRER_POLICY</code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/zh-hans/4.0/ref/settings/#std-setting-SECURE_SSL_HOST\"><code class=\"xref std std-setting docutils literal notranslate\">SECURE_SSL_HOST</code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/zh-hans/4.0/ref/settings/#std-setting-SECURE_SSL_REDIRECT\"><code class=\"xref std std-setting docutils literal notranslate\">SECURE_SSL_REDIRECT</code></a></p></li>\n</ul>\n<section id=\"http-strict-transport-security\">\n<span id=\"id2\"></span><h4>HTTP 严格传输安全<a class=\"heading-anchor\" href=\"#http-strict-transport-security\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>对于只能通过 HTTPS 访问的网站，你可以通过设置 <a class=\"reference external\" href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security\">&quot;Strict-Transport-Security&quot; 头</a> 来指示现代浏览器拒绝通过不安全的连接连接到你的域名（在给定的时间内）。这可以减少你受到一些 SSL 剥离中间人（MITM）的攻击。</p>\n<p>如果你将 <a class=\"reference internal\" href=\"/zh-hans/4.0/ref/settings/#std-setting-SECURE_HSTS_SECONDS\"><code class=\"xref std std-setting docutils literal notranslate\">SECURE_HSTS_SECONDS</code></a> 设置为一个非零的整数值，<code class=\"docutils literal notranslate\">SecurityMiddleware</code> 将为你在所有 HTTPS 响应中设置这个头。</p>\n<p>When enabling HSTS, it's a good idea to first use a small value for testing,\nfor example, <a class=\"reference internal\" href=\"/zh-hans/4.0/ref/settings/#std-setting-SECURE_HSTS_SECONDS\"><code class=\"xref std std-setting docutils literal notranslate\">SECURE_HSTS_SECONDS = 3600</code></a> for one\nhour. Each time a web browser sees the HSTS header from your site, it will\nrefuse to communicate non-securely (using HTTP) with your domain for the given\nperiod of time. Once you confirm that all assets are served securely on your\nsite (i.e. HSTS didn't break anything), it's a good idea to increase this value\nso that infrequent visitors will be protected (31536000 seconds, i.e. 1 year,\nis common).</p>\n<p>此外，如果你将 <a class=\"reference internal\" href=\"/zh-hans/4.0/ref/settings/#std-setting-SECURE_HSTS_INCLUDE_SUBDOMAINS\"><code class=\"xref std std-setting docutils literal notranslate\">SECURE_HSTS_INCLUDE_SUBDOMAINS</code></a> 设置为 <code class=\"docutils literal notranslate\">True</code>，<code class=\"docutils literal notranslate\">SecurityMiddleware</code> 将在 <code class=\"docutils literal notranslate\">Strict-Transport-Security</code> 头中添加 <code class=\"docutils literal notranslate\">includeSubDomains</code> 指令。建议这样做（假设所有的子域都只使用 HTTPS 服务），否则你的网站仍然可能通过不安全的连接到子域而受到攻击。</p>\n<p>如果你希望将你的网站提交到 <a class=\"reference external\" href=\"https://hstspreload.org/\">浏览器预加载列表</a> ，请将 <a class=\"reference internal\" href=\"/zh-hans/4.0/ref/settings/#std-setting-SECURE_HSTS_PRELOAD\"><code class=\"xref std std-setting docutils literal notranslate\">SECURE_HSTS_PRELOAD</code></a> 设置为 <code class=\"docutils literal notranslate\">True</code>。这样就会把 <code class=\"docutils literal notranslate\">preload</code> 指令附加到 <code class=\"docutils literal notranslate\">Strict-Transport-Security</code> 头。</p>\n<aside class=\"admonition admonition-warning\" role=\"note\">\n<p class=\"admonition-title\">Warning</p>\n<p>HSTS 策略适用于你的整个域，而不仅仅是你设置响应头的 URL。因此，你应该只在你的整个域名只通过 HTTPS 服务时使用它。</p>\n<p>适当尊重 HSTS 头的浏览器将拒绝允许用户绕过警告，并连接到使用过期、自签名或其他无效 SSL 证书的网站。如果你使用 HSTS，请确保你的证书处于良好状态，并保持这种状态！</p>\n</aside>\n<aside class=\"admonition admonition-note\" role=\"note\">\n<p class=\"admonition-title\">Note</p>\n<p>如果你部署在负载平衡器或反向代理服务器后面，而 <code class=\"docutils literal notranslate\">Strict-Transport-Security</code> 头没有被添加到你的响应中，这可能是因为 Django 没有意识到它是在一个安全的连接上；你可能需要设置 <a class=\"reference internal\" href=\"/zh-hans/4.0/ref/settings/#std-setting-SECURE_PROXY_SSL_HEADER\"><code class=\"xref std std-setting docutils literal notranslate\">SECURE_PROXY_SSL_HEADER</code></a> 设置。</p>\n</aside>\n</section>\n<section id=\"referrer-policy\">\n<span id=\"id4\"></span><h4>Referrer 政策<a class=\"heading-anchor\" href=\"#referrer-policy\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>浏览器使用 <a class=\"reference external\" href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referer\">referer 头</a> 作为向网站发送关于用户如何到达那里的信息的一种方式。当用户点击一个链接时，浏览器将发送链接页面的完整 URL 作为 referrer。虽然这对某些目的来说可能很有用——例如查明谁在链接到你的网站——但它也可能引起隐私问题，因为它告诉一个网站，一个用户正在访问另一个网站。</p>\n<p>一些浏览器能够接受关于是否应该在用户点击链接时发送 HTTP <code class=\"docutils literal notranslate\">Referer</code> 头的提示；这种提示通过 <a class=\"reference external\" href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy\">Referrer-Policy 头</a> 提供。这个头可以向浏览器建议三种行为中的任何一种：</p>\n<ul class=\"simple\">\n<li><p>完整 URL：在 <code class=\"docutils literal notranslate\">Referer</code> 头中发送整个URL。例如，如果用户访问 <code class=\"docutils literal notranslate\">https://example.com/page.html</code>，<code class=\"docutils literal notranslate\">Referer</code> 头将包含 <code class=\"docutils literal notranslate\">&quot;https://example.com/page.html&quot;</code>。</p></li>\n<li><p>仅起源：只发送 referrer 中的“起源”。起源由方案、主机和（可选）端口号组成。例如，如果用户访问的是 <code class=\"docutils literal notranslate\">https://example.com/page.html</code>，起源就是 <code class=\"docutils literal notranslate\">https://example.com/</code>。</p></li>\n<li><p>无 referrer：完全不发送 <code class=\"docutils literal notranslate\">Referer</code> 头。</p></li>\n</ul>\n<p>有两种类型的情况，这个头可以告诉浏览器要注意：</p>\n<ul class=\"simple\">\n<li><p>同源与跨源：从 <code class=\"docutils literal notranslate\">https://example.com/1.html</code> 到 <code class=\"docutils literal notranslate\">https://example.com/2.html</code> 的链接为同源链接。从 <code class=\"docutils literal notranslate\">https://example.com/page.html</code> 到 <code class=\"docutils literal notranslate\">https://not.example.com/page.html</code> 的链接为跨源链接。</p></li>\n<li><p>协议降级：如果包含链接的页面是通过 HTTPS 服务的，但被链接的页面不是通过 HTTPS 服务的，就会发生降级。</p></li>\n</ul>\n<aside class=\"admonition admonition-warning\" role=\"note\">\n<p class=\"admonition-title\">Warning</p>\n<p>When your site is served via HTTPS, <a class=\"reference internal\" href=\"/zh-hans/4.0/ref/csrf/#how-csrf-works\"><span class=\"std std-ref\">Django's CSRF protection system</span></a> requires the <code class=\"docutils literal notranslate\">Referer</code> header to be present, so\ncompletely disabling the <code class=\"docutils literal notranslate\">Referer</code> header will interfere with CSRF\nprotection. To gain most of the benefits of disabling <code class=\"docutils literal notranslate\">Referer</code> headers\nwhile also keeping CSRF protection, consider enabling only same-origin\nreferrers.</p>\n</aside>\n<p><code class=\"docutils literal notranslate\">SecurityMiddleware</code> 可以根据 <a class=\"reference internal\" href=\"/zh-hans/4.0/ref/settings/#std-setting-SECURE_REFERRER_POLICY\"><code class=\"xref std std-setting docutils literal notranslate\">SECURE_REFERRER_POLICY</code></a> 设置，为你设置 <code class=\"docutils literal notranslate\">Referrer-Policy</code> 头（注意拼写：当用户点击链接时，浏览器会发送一个 <code class=\"docutils literal notranslate\">Referer</code> 头，但指示浏览器是否这样做的头是拼写为 <code class=\"docutils literal notranslate\">Referrer-Policy</code>）。该设置的有效值为：</p>\n<dl class=\"simple\">\n<dt><code class=\"docutils literal notranslate\">no-referrer</code></dt><dd><p>指示浏览器对在本网站上点击的链接不发送 referrer。</p>\n</dd>\n<dt><code class=\"docutils literal notranslate\">no-referrer-when-downgrade</code></dt><dd><p>指示浏览器发送完整的 URL 作为 referrer，但只有在没有发生协议降级的情况下。</p>\n</dd>\n<dt><code class=\"docutils literal notranslate\">origin</code></dt><dd><p>指示浏览器只发送起源，而不是完整的 URL 作为 referrer。</p>\n</dd>\n<dt><code class=\"docutils literal notranslate\">origin-when-cross-origin</code></dt><dd><p>指示浏览器发送完整的 URL 作为同源链接的 referrer，而只发送起源给跨源链接。</p>\n</dd>\n<dt><code class=\"docutils literal notranslate\">same-origin</code></dt><dd><p>指示浏览器发送完整的 URL，但只针对同源链接。对于跨源链接，将不发送 referrer。</p>\n</dd>\n<dt><code class=\"docutils literal notranslate\">strict-origin</code></dt><dd><p>指示浏览器只发送起源，而不是完整的 URL，并在协议降级时不发送 referrer。</p>\n</dd>\n<dt><code class=\"docutils literal notranslate\">strict-origin-when-cross-origin</code></dt><dd><p>当链接为同源且不发生协议降级时，指示浏览器发送完整的 URL；当链接为跨源且不发生协议降级时，只发送起源；当发生协议降级时，不发送 referrer。</p>\n</dd>\n<dt><code class=\"docutils literal notranslate\">unsafe-url</code></dt><dd><p>指示浏览器始终发送完整的 URL 作为 referrer。</p>\n</dd>\n</dl>\n<aside class=\"admonition-unknown-policy-values admonition\" role=\"note\">\n<p class=\"admonition-title\">未知政策值</p>\n<p>当一个策略值被用户代理认为 <a class=\"reference external\" href=\"https://w3c.github.io/webappsec-referrer-policy/#unknown-policy-values\">未知</a> 时，可以指定多个策略值以提供后备。最后一个被理解的指定值优先。为了支持这一点，可以在 <a class=\"reference internal\" href=\"/zh-hans/4.0/ref/settings/#std-setting-SECURE_REFERRER_POLICY\"><code class=\"xref std std-setting docutils literal notranslate\">SECURE_REFERRER_POLICY</code></a> 中使用一个可迭代对象或逗号分隔的字符串。</p>\n</aside>\n</section>\n<section id=\"cross-origin-opener-policy\">\n<span id=\"id8\"></span><h4>Cross-Origin Opener Policy<a class=\"heading-anchor\" href=\"#cross-origin-opener-policy\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<aside class=\"version-note version-added\" data-version=\"4.0\" role=\"note\">\n<p class=\"version-note-title\">New in Django 4.0</p></aside>\n<p>Some browsers have the ability to isolate top-level windows from other\ndocuments by putting them in a separate browsing context group based on the\nvalue of the <a class=\"reference external\" href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy\">Cross-Origin Opener Policy</a> (COOP) header. If a document that\nis isolated in this way opens a cross-origin popup window, the popup’s\n<code class=\"docutils literal notranslate\">window.opener</code> property will be <code class=\"docutils literal notranslate\">null</code>. Isolating windows using COOP is a\ndefense-in-depth protection against cross-origin attacks, especially those like\nSpectre which allowed exfiltration of data loaded into a shared browsing\ncontext.</p>\n<p><code class=\"docutils literal notranslate\">SecurityMiddleware</code> can set the <code class=\"docutils literal notranslate\">Cross-Origin-Opener-Policy</code> header for\nyou, based on the <a class=\"reference internal\" href=\"/zh-hans/4.0/ref/settings/#std-setting-SECURE_CROSS_ORIGIN_OPENER_POLICY\"><code class=\"xref std std-setting docutils literal notranslate\">SECURE_CROSS_ORIGIN_OPENER_POLICY</code></a> setting. The\nvalid values for this setting are:</p>\n<dl class=\"simple\">\n<dt><code class=\"docutils literal notranslate\">same-origin</code></dt><dd><p>Isolates the browsing context exclusively to same-origin documents.\nCross-origin documents are not loaded in the same browsing context. This\nis the default and most secure option.</p>\n</dd>\n<dt><code class=\"docutils literal notranslate\">same-origin-allow-popups</code></dt><dd><p>Isolates the browsing context to same-origin documents or those which\neither don't set COOP or which opt out of isolation by setting a COOP of\n<code class=\"docutils literal notranslate\">unsafe-none</code>.</p>\n</dd>\n<dt><code class=\"docutils literal notranslate\">unsafe-none</code></dt><dd><p>Allows the document to be added to its opener's browsing context group\nunless the opener itself has a COOP of <code class=\"docutils literal notranslate\">same-origin</code> or\n<code class=\"docutils literal notranslate\">same-origin-allow-popups</code>.</p>\n</dd>\n</dl>\n</section>\n<section id=\"x-content-type-options-nosniff\">\n<span id=\"x-content-type-options\"></span><h4><code class=\"docutils literal notranslate\">X-Content-Type-Options: nosniff</code><a class=\"heading-anchor\" href=\"#x-content-type-options-nosniff\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>一些浏览器会试图猜测它们获取的资源的内容类型，覆盖 <code class=\"docutils literal notranslate\">Content-Type</code> 头。虽然这可以帮助显示配置不当的服务器的网站，但也会带来安全风险。</p>\n<p>如果你的网站提供用户上传的文件，恶意用户可能会上传一个特制的文件，当你认为它是无害的东西时，该文件会被浏览器解释为 HTML 或 JavaScript。</p>\n<p>为了防止浏览器猜测内容类型，并迫使它总是使用 <code class=\"docutils literal notranslate\">Content-Type</code> 头中提供的类型，你可以传递 <a class=\"reference external\" href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options\">X-Content-Type-Options: nosniff</a> 头。 如果 <a class=\"reference internal\" href=\"/zh-hans/4.0/ref/settings/#std-setting-SECURE_CONTENT_TYPE_NOSNIFF\"><code class=\"xref std std-setting docutils literal notranslate\">SECURE_CONTENT_TYPE_NOSNIFF</code></a> 设置为 <code class=\"docutils literal notranslate\">True</code>，<code class=\"docutils literal notranslate\">SecurityMiddleware</code> 将对所有的响应进行这样的操作。</p>\n<p>Note that in most deployment situations where Django isn't involved in serving\nuser-uploaded files, this setting won't help you. For example, if your\n<a class=\"reference internal\" href=\"/zh-hans/4.0/ref/settings/#std-setting-MEDIA_URL\"><code class=\"xref std std-setting docutils literal notranslate\">MEDIA_URL</code></a> is served directly by your front-end web server (nginx,\nApache, etc.) then you'd want to set this header there. On the other hand, if\nyou are using Django to do something like require authorization in order to\ndownload files and you cannot set the header using your web server, this\nsetting will be useful.</p>\n</section>\n<section id=\"ssl-redirect\">\n<span id=\"id11\"></span><h4>SSL 重定向<a class=\"heading-anchor\" href=\"#ssl-redirect\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>如果你的网站同时提供 HTTP 和 HTTPS 连接，大多数用户最终会默认使用不安全的连接。为了达到最佳的安全性，你应该将所有的 HTTP 连接重定向到 HTTPS。</p>\n<p>如果你将 <a class=\"reference internal\" href=\"/zh-hans/4.0/ref/settings/#std-setting-SECURE_SSL_REDIRECT\"><code class=\"xref std std-setting docutils literal notranslate\">SECURE_SSL_REDIRECT</code></a> 设置为 True，<code class=\"docutils literal notranslate\">SecurityMiddleware</code> 将永久（HTTP 301）重定向所有 HTTP 连接到 HTTPS。</p>\n<aside class=\"admonition admonition-note\" role=\"note\">\n<p class=\"admonition-title\">Note</p>\n<p>出于性能方面的考虑，最好在 Django 之外，在前端负载均衡器或反向代理服务器（如 <a class=\"reference external\" href=\"https://nginx.org/\">nginx</a> ）中做这些重定向。 <a class=\"reference internal\" href=\"/zh-hans/4.0/ref/settings/#std-setting-SECURE_SSL_REDIRECT\"><code class=\"xref std std-setting docutils literal notranslate\">SECURE_SSL_REDIRECT</code></a> 是为了在部署情况下，这不是一个选项。</p>\n</aside>\n<p>如果 <a class=\"reference internal\" href=\"/zh-hans/4.0/ref/settings/#std-setting-SECURE_SSL_HOST\"><code class=\"xref std std-setting docutils literal notranslate\">SECURE_SSL_HOST</code></a> 设置有一个值，所有的重定向将被发送到该主机，而不是最初要求的主机。</p>\n<p>如果你的网站上有几个页面应该通过 HTTP 提供，而不是重定向到 HTTPS，你可以在 <a class=\"reference internal\" href=\"/zh-hans/4.0/ref/settings/#std-setting-SECURE_REDIRECT_EXEMPT\"><code class=\"xref std std-setting docutils literal notranslate\">SECURE_REDIRECT_EXEMPT</code></a> 设置中列出正则表达式来匹配这些 URL。</p>\n<aside class=\"admonition admonition-note\" role=\"note\">\n<p class=\"admonition-title\">Note</p>\n<p>如果你部署在负载均衡器或反向代理服务器后面，而 Django 似乎无法判断一个请求是否真的已经安全，你可能需要设置 <a class=\"reference internal\" href=\"/zh-hans/4.0/ref/settings/#std-setting-SECURE_PROXY_SSL_HEADER\"><code class=\"xref std std-setting docutils literal notranslate\">SECURE_PROXY_SSL_HEADER</code></a> 配置。</p>\n</aside>\n</section>\n</section>\n<section id=\"module-django.contrib.sessions.middleware\">\n<span id=\"session-middleware\"></span><h3>会话中间件<a class=\"heading-anchor\" href=\"#module-django.contrib.sessions.middleware\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<dl class=\"py class\">\n<dt class=\"sig sig-object py\" id=\"django.contrib.sessions.middleware.SessionMiddleware\">\n<em class=\"property\"><span class=\"k\">class</span> </em><span class=\"sig-name descname\">SessionMiddleware</span><a class=\"heading-anchor\" href=\"#django.contrib.sessions.middleware.SessionMiddleware\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>启用会话支持。参见 <a class=\"reference internal\" href=\"/zh-hans/4.0/topics/http/sessions/\"><span class=\"doc\">会话文档</span></a>。</p>\n</section>\n<section id=\"module-django.contrib.sites.middleware\">\n<span id=\"site-middleware\"></span><h3>站点中间件<a class=\"heading-anchor\" href=\"#module-django.contrib.sites.middleware\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<dl class=\"py class\">\n<dt class=\"sig sig-object py\" id=\"django.contrib.sites.middleware.CurrentSiteMiddleware\">\n<em class=\"property\"><span class=\"k\">class</span> </em><span class=\"sig-name descname\">CurrentSiteMiddleware</span><a class=\"heading-anchor\" href=\"#django.contrib.sites.middleware.CurrentSiteMiddleware\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>将代表当前站点的 <code class=\"docutils literal notranslate\">site</code> 属性添加到每个传入的 <code class=\"docutils literal notranslate\">HttpRequest</code> 对象中。参见 <a class=\"reference internal\" href=\"/zh-hans/4.0/ref/contrib/sites/#site-middleware\"><span class=\"std std-ref\">站点文档</span></a>。</p>\n</section>\n<section id=\"module-django.contrib.auth.middleware\">\n<span id=\"authentication-middleware\"></span><h3>验证中间件<a class=\"heading-anchor\" href=\"#module-django.contrib.auth.middleware\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<dl class=\"py class\">\n<dt class=\"sig sig-object py\" id=\"django.contrib.auth.middleware.AuthenticationMiddleware\">\n<em class=\"property\"><span class=\"k\">class</span> </em><span class=\"sig-name descname\">AuthenticationMiddleware</span><a class=\"heading-anchor\" href=\"#django.contrib.auth.middleware.AuthenticationMiddleware\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>Adds the <code class=\"docutils literal notranslate\">user</code> attribute, representing the currently-logged-in user, to\nevery incoming <code class=\"docutils literal notranslate\">HttpRequest</code> object. See <a class=\"reference internal\" href=\"/zh-hans/4.0/topics/auth/default/#auth-web-requests\"><span class=\"std std-ref\">Authentication in web requests</span></a>.</p>\n<dl class=\"py class\">\n<dt class=\"sig sig-object py\" id=\"django.contrib.auth.middleware.RemoteUserMiddleware\">\n<em class=\"property\"><span class=\"k\">class</span> </em><span class=\"sig-name descname\">RemoteUserMiddleware</span><a class=\"heading-anchor\" href=\"#django.contrib.auth.middleware.RemoteUserMiddleware\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>Middleware for utilizing web server provided authentication. See\n<a class=\"reference internal\" href=\"/zh-hans/4.0/howto/auth-remote-user/\"><span class=\"doc\">使用 REMOTE_USER 进行身份验证</span></a> for usage details.</p>\n<dl class=\"py class\">\n<dt class=\"sig sig-object py\" id=\"django.contrib.auth.middleware.PersistentRemoteUserMiddleware\">\n<em class=\"property\"><span class=\"k\">class</span> </em><span class=\"sig-name descname\">PersistentRemoteUserMiddleware</span><a class=\"heading-anchor\" href=\"#django.contrib.auth.middleware.PersistentRemoteUserMiddleware\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>Middleware for utilizing web server provided authentication when enabled only\non the login page. See <a class=\"reference internal\" href=\"/zh-hans/4.0/howto/auth-remote-user/#persistent-remote-user-middleware-howto\"><span class=\"std std-ref\">仅在登录界面使用 REMOTE_USER</span></a> for usage\ndetails.</p>\n</section>\n<section id=\"csrf-protection-middleware\">\n<h3>CSRF 保护中间件<a class=\"heading-anchor\" href=\"#csrf-protection-middleware\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<dl class=\"py class\">\n<dt class=\"sig sig-object py\" id=\"django.middleware.csrf.CsrfViewMiddleware\">\n<em class=\"property\"><span class=\"k\">class</span> </em><span class=\"sig-name descname\">CsrfViewMiddleware</span><a class=\"heading-anchor\" href=\"#django.middleware.csrf.CsrfViewMiddleware\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>通过在 POST 表单中添加隐藏的表单字段，并检查请求的正确值，增加对跨站点伪造请求的保护。请参阅 <a class=\"reference internal\" href=\"/zh-hans/4.0/ref/csrf/\"><span class=\"doc\">跨站点伪造请求保护文档</span></a>。</p>\n</section>\n<section id=\"x-frame-options-middleware\">\n<h3><code class=\"docutils literal notranslate\">X-Frame-Options</code> 中间件<a class=\"heading-anchor\" href=\"#x-frame-options-middleware\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<dl class=\"py class\">\n<dt class=\"sig sig-object py\" id=\"django.middleware.clickjacking.XFrameOptionsMiddleware\">\n<em class=\"property\"><span class=\"k\">class</span> </em><span class=\"sig-name descname\">XFrameOptionsMiddleware</span><a class=\"heading-anchor\" href=\"#django.middleware.clickjacking.XFrameOptionsMiddleware\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>简单的 <a class=\"reference internal\" href=\"/zh-hans/4.0/ref/clickjacking/\"><span class=\"doc\">通过 X-Frame-Options 头的点击劫持保护</span></a>。</p>\n</section>\n</section>\n<section id=\"middleware-ordering\">\n<span id=\"id12\"></span><h2>中间件顺序<a class=\"heading-anchor\" href=\"#middleware-ordering\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>下面是关于各种 Django 中间件类的排序的一些提示：</p>\n<ol class=\"arabic\">\n<li><p><a class=\"reference internal\" href=\"#django.middleware.security.SecurityMiddleware\" title=\"django.middleware.security.SecurityMiddleware\"><code class=\"xref py py-class docutils literal notranslate\">SecurityMiddleware</code></a></p>\n<p>如果你要开启 SSL 重定向，它应该排在列表的最前面，因为这样可以避免运行一堆其他不必要的中间件。</p>\n</li>\n<li><p><a class=\"reference internal\" href=\"#django.middleware.cache.UpdateCacheMiddleware\" title=\"django.middleware.cache.UpdateCacheMiddleware\"><code class=\"xref py py-class docutils literal notranslate\">UpdateCacheMiddleware</code></a></p>\n<p>在修改 <code class=\"docutils literal notranslate\">Vary</code> 头（<code class=\"docutils literal notranslate\">SessionMiddleware</code>、<code class=\"docutils literal notranslate\">GZipMiddleware</code>、<code class=\"docutils literal notranslate\">LocaleMiddleware</code>）之前。</p>\n</li>\n<li><p><a class=\"reference internal\" href=\"#django.middleware.gzip.GZipMiddleware\" title=\"django.middleware.gzip.GZipMiddleware\"><code class=\"xref py py-class docutils literal notranslate\">GZipMiddleware</code></a></p>\n<p>在任何可能改变或使用响应体的中间件之前。</p>\n<p>在 <code class=\"docutils literal notranslate\">UpdateCacheMiddleware</code> 之后：修改 <code class=\"docutils literal notranslate\">Vary</code> 头。</p>\n</li>\n<li><p><a class=\"reference internal\" href=\"#django.contrib.sessions.middleware.SessionMiddleware\" title=\"django.contrib.sessions.middleware.SessionMiddleware\"><code class=\"xref py py-class docutils literal notranslate\">SessionMiddleware</code></a></p>\n<p>在任何可能引发异常触发错误视图的中间件之前（如 <a class=\"reference internal\" href=\"/zh-hans/4.0/ref/exceptions/#django.core.exceptions.PermissionDenied\" title=\"django.core.exceptions.PermissionDenied\"><code class=\"xref py py-exc docutils literal notranslate\">PermissionDenied</code></a>），如果你使用的是 <a class=\"reference internal\" href=\"/zh-hans/4.0/ref/settings/#std-setting-CSRF_USE_SESSIONS\"><code class=\"xref std std-setting docutils literal notranslate\">CSRF_USE_SESSIONS</code></a>。</p>\n<p>在 <code class=\"docutils literal notranslate\">UpdateCacheMiddleware</code> 之后：修改 <code class=\"docutils literal notranslate\">Vary</code> 头。</p>\n</li>\n<li><p><a class=\"reference internal\" href=\"#django.middleware.http.ConditionalGetMiddleware\" title=\"django.middleware.http.ConditionalGetMiddleware\"><code class=\"xref py py-class docutils literal notranslate\">ConditionalGetMiddleware</code></a></p>\n<p>在任何可能改变响应的中间件之前（它设置 <code class=\"docutils literal notranslate\">ETag</code> 头）。</p>\n<p>在 <code class=\"docutils literal notranslate\">GZipMiddleware</code> 之后，这样它就不会在 gzip 压缩后的内容上计算 <code class=\"docutils literal notranslate\">ETag</code> 头。</p>\n</li>\n<li><p><a class=\"reference internal\" href=\"#django.middleware.locale.LocaleMiddleware\" title=\"django.middleware.locale.LocaleMiddleware\"><code class=\"xref py py-class docutils literal notranslate\">LocaleMiddleware</code></a></p>\n<p>最上面的一个，仅次于 <code class=\"docutils literal notranslate\">SessionMiddleware</code> （使用会话数据）和 <code class=\"docutils literal notranslate\">UpdateCacheMiddleware</code> （修改 <code class=\"docutils literal notranslate\">Vary</code> 头）。</p>\n</li>\n<li><p><a class=\"reference internal\" href=\"#django.middleware.common.CommonMiddleware\" title=\"django.middleware.common.CommonMiddleware\"><code class=\"xref py py-class docutils literal notranslate\">CommonMiddleware</code></a></p>\n<p>在任何可能改变响应的中间件之前（它设置 <code class=\"docutils literal notranslate\">Content-Length</code> 头）。出现在 <code class=\"docutils literal notranslate\">CommonMiddleware</code> 之前并改变响应的中间件必须重置 <code class=\"docutils literal notranslate\">Content-Length</code>。</p>\n<p>靠近顶部：当 <a class=\"reference internal\" href=\"/zh-hans/4.0/ref/settings/#std-setting-APPEND_SLASH\"><code class=\"xref std std-setting docutils literal notranslate\">APPEND_SLASH</code></a> 或 <a class=\"reference internal\" href=\"/zh-hans/4.0/ref/settings/#std-setting-PREPEND_WWW\"><code class=\"xref std std-setting docutils literal notranslate\">PREPEND_WWW</code></a> 设置为 <code class=\"docutils literal notranslate\">True</code> 时，它会重定向。</p>\n<p>在 <code class=\"docutils literal notranslate\">SessionMiddleware</code> 之后，如果你使用 <a class=\"reference internal\" href=\"/zh-hans/4.0/ref/settings/#std-setting-CSRF_USE_SESSIONS\"><code class=\"xref std std-setting docutils literal notranslate\">CSRF_USE_SESSIONS</code></a>。</p>\n</li>\n<li><p><a class=\"reference internal\" href=\"#django.middleware.csrf.CsrfViewMiddleware\" title=\"django.middleware.csrf.CsrfViewMiddleware\"><code class=\"xref py py-class docutils literal notranslate\">CsrfViewMiddleware</code></a></p>\n<p>在任何假设 CSRF 攻击已经被处理的视图中间件之前。</p>\n<p>在 <a class=\"reference internal\" href=\"#django.contrib.auth.middleware.RemoteUserMiddleware\" title=\"django.contrib.auth.middleware.RemoteUserMiddleware\"><code class=\"xref py py-class docutils literal notranslate\">RemoteUserMiddleware</code></a>，或任何其他可能执行登录的认证中间件，从而旋转 CSRF 令牌，然后再向下调用中间件链。</p>\n<p>在 <code class=\"docutils literal notranslate\">SessionMiddleware</code> 之后，如果你使用 <a class=\"reference internal\" href=\"/zh-hans/4.0/ref/settings/#std-setting-CSRF_USE_SESSIONS\"><code class=\"xref std std-setting docutils literal notranslate\">CSRF_USE_SESSIONS</code></a>。</p>\n</li>\n<li><p><a class=\"reference internal\" href=\"#django.contrib.auth.middleware.AuthenticationMiddleware\" title=\"django.contrib.auth.middleware.AuthenticationMiddleware\"><code class=\"xref py py-class docutils literal notranslate\">AuthenticationMiddleware</code></a></p>\n<p><code class=\"docutils literal notranslate\">SessionMiddleware</code> 之后：使用会话存储。</p>\n</li>\n<li><p><a class=\"reference internal\" href=\"#django.contrib.messages.middleware.MessageMiddleware\" title=\"django.contrib.messages.middleware.MessageMiddleware\"><code class=\"xref py py-class docutils literal notranslate\">MessageMiddleware</code></a></p>\n<p><code class=\"docutils literal notranslate\">SessionMiddleware</code> 之后：可以使用基于会话的存储。</p>\n</li>\n<li><p><a class=\"reference internal\" href=\"#django.middleware.cache.FetchFromCacheMiddleware\" title=\"django.middleware.cache.FetchFromCacheMiddleware\"><code class=\"xref py py-class docutils literal notranslate\">FetchFromCacheMiddleware</code></a></p>\n<p>在任何修改 <code class=\"docutils literal notranslate\">Vary</code> 头的中间件之后：该头用于为缓存哈希键选取一个值。</p>\n</li>\n<li><p><a class=\"reference internal\" href=\"/zh-hans/4.0/ref/contrib/flatpages/#django.contrib.flatpages.middleware.FlatpageFallbackMiddleware\" title=\"django.contrib.flatpages.middleware.FlatpageFallbackMiddleware\"><code class=\"xref py py-class docutils literal notranslate\">FlatpageFallbackMiddleware</code></a></p>\n<p>应该是接近底部，因为这是一种最后的中间件。</p>\n</li>\n<li><p><a class=\"reference internal\" href=\"/zh-hans/4.0/ref/contrib/redirects/#django.contrib.redirects.middleware.RedirectFallbackMiddleware\" title=\"django.contrib.redirects.middleware.RedirectFallbackMiddleware\"><code class=\"xref py py-class docutils literal notranslate\">RedirectFallbackMiddleware</code></a></p>\n<p>应该是接近底部，因为这是一种最后的中间件。</p>\n</li>\n</ol>\n</section>","rootId":"module-django.middleware","toc":[{"title":"可用的中间件","anchor":"available-middleware","children":[{"title":"缓存中间件","anchor":"module-django.middleware.cache","children":[]},{"title":"“通用”中间件","anchor":"module-django.middleware.common","children":[]},{"title":"GZip 中间件","anchor":"module-django.middleware.gzip","children":[]},{"title":"条件 GET 中间件","anchor":"module-django.middleware.http","children":[]},{"title":"本地化中间件","anchor":"module-django.middleware.locale","children":[]},{"title":"消息中间件","anchor":"module-django.contrib.messages.middleware","children":[]},{"title":"安全中间件","anchor":"module-django.middleware.security","children":[{"title":"HTTP 严格传输安全","anchor":"http-strict-transport-security","children":[]},{"title":"Referrer 政策","anchor":"referrer-policy","children":[]},{"title":"Cross-Origin Opener Policy","anchor":"cross-origin-opener-policy","children":[]},{"title":"X-Content-Type-Options: nosniff","anchor":"x-content-type-options-nosniff","children":[]},{"title":"SSL 重定向","anchor":"ssl-redirect","children":[]}]},{"title":"会话中间件","anchor":"module-django.contrib.sessions.middleware","children":[]},{"title":"站点中间件","anchor":"module-django.contrib.sites.middleware","children":[]},{"title":"验证中间件","anchor":"module-django.contrib.auth.middleware","children":[]},{"title":"CSRF 保护中间件","anchor":"csrf-protection-middleware","children":[]},{"title":"X-Frame-Options 中间件","anchor":"x-frame-options-middleware","children":[]}]},{"title":"中间件顺序","anchor":"middleware-ordering","children":[]}],"breadcrumbs":[{"docname":"ref/index","title":"API 参考","url":"/zh-hans/4.0/ref/"}],"prev":{"docname":"ref/logging","title":"日志","url":"/zh-hans/4.0/ref/logging/"},"next":{"docname":"ref/migration-operations","title":"迁移操作","url":"/zh-hans/4.0/ref/migration-operations/"},"formats":{"html":"/zh-hans/4.0/ref/middleware/","markdown":"/zh-hans/4.0/ref/middleware.md","json":"/zh-hans/4.0/ref/middleware.json"},"source":"https://github.com/django/django/blob/stable/4.0.x/docs/ref/middleware.txt","official":"https://docs.djangoproject.com/zh-hans/4.0/ref/middleware/","inVersions":["6.1","6.0","5.2","5.1","5.0","4.2","4.1","4.0","3.2","3.1","3.0","2.2","2.1","2.0"],"inLocales":["en","zh-hans","fr","ja","id","it","pt-br","ko","es","el","pl"]}