CINXE.COM

Middleware | Django documentation | Django

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="ROBOTS" content="ALL" /> <meta name="MSSmartTagsPreventParsing" content="true" /> <meta name="Copyright" content="Django Software Foundation" /> <meta name="keywords" content="Python, Django, framework, open-source" /> <meta name="description" content="" /> <link rel="canonical" href="https://docs.djangoproject.com/en/5.1/ref/middleware/"> <link rel="alternate" hreflang="el" href="https://docs.djangoproject.com/el/3.0/ref/middleware/"> <link rel="alternate" hreflang="en" href="https://docs.djangoproject.com/en/3.0/ref/middleware/"> <link rel="alternate" hreflang="es" href="https://docs.djangoproject.com/es/3.0/ref/middleware/"> <link rel="alternate" hreflang="fr" href="https://docs.djangoproject.com/fr/3.0/ref/middleware/"> <link rel="alternate" hreflang="id" href="https://docs.djangoproject.com/id/3.0/ref/middleware/"> <link rel="alternate" hreflang="ja" href="https://docs.djangoproject.com/ja/3.0/ref/middleware/"> <link rel="alternate" hreflang="ko" href="https://docs.djangoproject.com/ko/3.0/ref/middleware/"> <link rel="alternate" hreflang="pl" href="https://docs.djangoproject.com/pl/3.0/ref/middleware/"> <link rel="alternate" hreflang="pt-br" href="https://docs.djangoproject.com/pt-br/3.0/ref/middleware/"> <link rel="alternate" hreflang="zh-hans" href="https://docs.djangoproject.com/zh-hans/3.0/ref/middleware/"> <link rel="search" type="application/opensearchdescription+xml" href="https://docs.djangoproject.com/en/3.0/search/description/" title="Django documentation"> <!-- Favicons --> <link rel="apple-touch-icon" href="https://static.djangoproject.com/img/icon-touch.e4872c4da341.png"> <link rel="icon" sizes="192x192" href="https://static.djangoproject.com/img/icon-touch.e4872c4da341.png"> <link rel="shortcut icon" href="https://static.djangoproject.com/img/favicon.6dbf28c0650e.ico"> <meta name="msapplication-TileColor" content="#113228"> <meta name="msapplication-TileImage" content="https://static.djangoproject.com/img/icon-tile.b01ac0ef9f67.png"> <meta name="theme-color" content="#0C4B33"> <meta property="og:title" content="Middleware | Django documentation" /> <meta property="og:description" content="The web framework for perfectionists with deadlines." /> <meta property="og:image" content="https://static.djangoproject.com/img/logos/django-logo-negative.1d528e2cb5fb.png" /> <meta property="og:image:alt" content="Django logo" /> <meta property="og:image:width" content="1200" /> <meta property="og:image:height" content="546" /> <meta property="og:image:type" content="image/png" /> <meta property="og:url" content="https://docs.djangoproject.com/en/3.0/ref/middleware/" /> <meta property="og:site_name" content="Django Project" /> <meta property="twitter:creator" content="djangoproject" /> <meta property="twitter:site" content="djangoproject" /> <meta property="twitter:card" content="summary"> <title>Middleware | Django documentation | Django</title> <link rel="stylesheet" href="https://static.djangoproject.com/css/output.fde294a46e8e.css" > <script src="https://static.djangoproject.com/js/lib/webfontloader/webfontloader.e75218f5f090.js"></script> <script> WebFont.load({ custom: { families: ['FontAwesome', 'Fira+Mono'], }, google: { families: ['Roboto:400italic,700italic,300,700,400:latin' ] }, classes: false, events: false, timeout: 1000 }); </script> <script src="https://static.djangoproject.com/js/lib/modernizr.3b36762e418a.js"></script> <script src="https://static.djangoproject.com/js/mod/switch-dark-mode.69777ee87b91.js"></script> </head> <body id="generic" class=""> <div role="banner" id="top"> <div class="container container--flex--wrap--mobile"> <a class="logo" href="https://www.djangoproject.com/">Django</a> <p class="meta">The web framework for perfectionists with deadlines.</p> <div class="mobile-toggle"> <button class="theme-toggle"> <div class="visually-hidden theme-label-when-auto">Toggle theme (current theme: auto)</div> <div class="visually-hidden theme-label-when-light">Toggle theme (current theme: light)</div> <div class="visually-hidden theme-label-when-dark">Toggle theme (current theme: dark)</div> <div class="visually-hidden">Toggle Light / Dark / Auto color theme</div> <svg aria-hidden="true" class="theme-icon-when-auto"> <use xlink:href="#icon-auto" /> </svg> <svg aria-hidden="true" class="theme-icon-when-dark"> <use xlink:href="#icon-moon" /> </svg> <svg aria-hidden="true" class="theme-icon-when-light"> <use xlink:href="#icon-sun" /> </svg> </button> </div> <button class="menu-button"> <i class="icon icon-reorder"></i> <span class="visuallyhidden">Menu</span> </button> <div role="navigation"> <ul> <li> <a href="https://www.djangoproject.com/start/overview/">Overview</a> </li> <li> <a href="https://www.djangoproject.com/download/">Download</a> </li> <li class="active"> <a href="https://docs.djangoproject.com/">Documentation</a> </li> <li> <a href="https://www.djangoproject.com/weblog/">News</a> </li> <li> <a href="https://www.djangoproject.com/community/">Community</a> </li> <li> <a href="https://github.com/django/django" target="_blank" rel="noopener">Code</a> </li> <li> <a href="https://code.djangoproject.com/">Issues</a> </li> <li> <a href="https://www.djangoproject.com/foundation/">About</a> </li> <li> <a href="https://www.djangoproject.com/fundraising/">&#9829; Donate</a> </li> <li> <button class="theme-toggle"> <div class="visually-hidden theme-label-when-auto">Toggle theme (current theme: auto)</div> <div class="visually-hidden theme-label-when-light">Toggle theme (current theme: light)</div> <div class="visually-hidden theme-label-when-dark">Toggle theme (current theme: dark)</div> <div class="visually-hidden">Toggle Light / Dark / Auto color theme</div> <svg aria-hidden="true" class="theme-icon-when-auto"> <use xlink:href="#icon-auto" /> </svg> <svg aria-hidden="true" class="theme-icon-when-dark"> <use xlink:href="#icon-moon" /> </svg> <svg aria-hidden="true" class="theme-icon-when-light"> <use xlink:href="#icon-sun" /> </svg> </button> </li> </ul> </div> </div> </div> <div class="copy-banner"> <div class="container container--flex container--flex--wrap--mobile "> <h1><a href="https://docs.djangoproject.com/en/3.0/">Documentation</a></h1> <form action="https://docs.djangoproject.com/en/3.0/search/" class="search form-input" role="search"> <label class="visuallyhidden" for="id_q">Search:</label> <input type="search" name="q" placeholder="Search 3.0 documentation" id="id_q"> <button type="submit"> <i class="icon icon-search"></i> <span class="visuallyhidden">Search</span> </button> </form> </div> </div> <div id="billboard"></div> <div class="container sidebar-right"> <div role="main"> <div id="version-switcher"> <ul id="faq-link"> <li class="current-link"> <a href="https://docs.djangoproject.com/en/3.0/faq/help/"> <span>Getting Help</span> </a> </li> </ul> <ul id="doc-languages" class="language-switcher doc-switcher"> <li class="other"> <a href="https://docs.djangoproject.com/el/3.0/ref/middleware/">el</a> </li> <li class="other"> <a href="https://docs.djangoproject.com/es/3.0/ref/middleware/">es</a> </li> <li class="other"> <a href="https://docs.djangoproject.com/fr/3.0/ref/middleware/">fr</a> </li> <li class="other"> <a href="https://docs.djangoproject.com/id/3.0/ref/middleware/">id</a> </li> <li class="other"> <a href="https://docs.djangoproject.com/ja/3.0/ref/middleware/">ja</a> </li> <li class="other"> <a href="https://docs.djangoproject.com/ko/3.0/ref/middleware/">ko</a> </li> <li class="other"> <a href="https://docs.djangoproject.com/pl/3.0/ref/middleware/">pl</a> </li> <li class="other"> <a href="https://docs.djangoproject.com/pt-br/3.0/ref/middleware/">pt-br</a> </li> <li class="other"> <a href="https://docs.djangoproject.com/zh-hans/3.0/ref/middleware/">zh-hans</a> </li> <li class="current" title="Click on the links on the left to switch to another language."> <span>Language: <strong>en</strong></span> </li> </ul> <ul id="doc-versions" class="version-switcher doc-switcher"> <li class="other"> <a href="https://docs.djangoproject.com/en/1.8/ref/middleware/">1.8</a> </li> <li class="other"> <a href="https://docs.djangoproject.com/en/1.10/ref/middleware/">1.10</a> </li> <li class="other"> <a href="https://docs.djangoproject.com/en/1.11/ref/middleware/">1.11</a> </li> <li class="other"> <a href="https://docs.djangoproject.com/en/2.0/ref/middleware/">2.0</a> </li> <li class="other"> <a href="https://docs.djangoproject.com/en/2.1/ref/middleware/">2.1</a> </li> <li class="other"> <a href="https://docs.djangoproject.com/en/2.2/ref/middleware/">2.2</a> </li> <li class="other"> <a href="https://docs.djangoproject.com/en/3.1/ref/middleware/">3.1</a> </li> <li class="other"> <a href="https://docs.djangoproject.com/en/3.2/ref/middleware/">3.2</a> </li> <li class="other"> <a href="https://docs.djangoproject.com/en/4.0/ref/middleware/">4.0</a> </li> <li class="other"> <a href="https://docs.djangoproject.com/en/4.1/ref/middleware/">4.1</a> </li> <li class="other"> <a href="https://docs.djangoproject.com/en/4.2/ref/middleware/">4.2</a> </li> <li class="other"> <a href="https://docs.djangoproject.com/en/5.0/ref/middleware/">5.0</a> </li> <li class="other"> <a href="https://docs.djangoproject.com/en/5.1/ref/middleware/">5.1</a> </li> <li class="other"> <a href="https://docs.djangoproject.com/en/dev/ref/middleware/">dev</a> </li> <li class="current" title="This document describes Django 3.0. Click on the links on the left to see other versions."> <span>Documentation version: <strong>3.0</strong> </span> </li> </ul> <ul id="backtotop-link"> <li class="current-link"> <a href="#top" aria-label="Back to top" class="icon-chevron-up-align"><i class="icon icon-chevron-up"></i></a> </li> </ul> </div> <div id="docs-content"> <div class="section" id="s-module-django.middleware"> <span id="s-middleware"></span><span id="module-django.middleware"></span><span id="middleware"></span><h1>Middleware<a class="headerlink" href="#module-django.middleware" title="Permalink to this headline">¶</a></h1> <p>This document explains all middleware components that come with Django. For information on how to use them and how to write your own middleware, see the <a class="reference internal" href="../../topics/http/middleware/"><span class="doc">middleware usage guide</span></a>.</p> <div class="section" id="s-available-middleware"> <span id="available-middleware"></span><h2>Available middleware<a class="headerlink" href="#available-middleware" title="Permalink to this headline">¶</a></h2> <div class="section" id="s-module-django.middleware.cache"> <span id="s-cache-middleware"></span><span id="module-django.middleware.cache"></span><span id="cache-middleware"></span><h3>Cache middleware<a class="headerlink" href="#module-django.middleware.cache" title="Permalink to this headline">¶</a></h3> <dl class="class"> <dt id="django.middleware.cache.UpdateCacheMiddleware"> <em class="property">class </em><code class="descname">UpdateCacheMiddleware</code><a class="headerlink" href="#django.middleware.cache.UpdateCacheMiddleware" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="class"> <dt id="django.middleware.cache.FetchFromCacheMiddleware"> <em class="property">class </em><code class="descname">FetchFromCacheMiddleware</code><a class="headerlink" href="#django.middleware.cache.FetchFromCacheMiddleware" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>Enable the site-wide cache. If these are enabled, each Django-powered page will be cached for as long as the <a class="reference internal" href="../settings/#std:setting-CACHE_MIDDLEWARE_SECONDS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CACHE_MIDDLEWARE_SECONDS</span></code></a> setting defines. See the <a class="reference internal" href="../../topics/cache/"><span class="doc">cache documentation</span></a>.</p> </div> <div class="section" id="s-module-django.middleware.common"> <span id="s-common-middleware"></span><span id="module-django.middleware.common"></span><span id="common-middleware"></span><h3>“Common” middleware<a class="headerlink" href="#module-django.middleware.common" title="Permalink to this headline">¶</a></h3> <dl class="class"> <dt id="django.middleware.common.CommonMiddleware"> <em class="property">class </em><code class="descname">CommonMiddleware</code><a class="headerlink" href="#django.middleware.common.CommonMiddleware" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>Adds a few conveniences for perfectionists:</p> <ul> <li><p class="first">Forbids access to user agents in the <a class="reference internal" href="../settings/#std:setting-DISALLOWED_USER_AGENTS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">DISALLOWED_USER_AGENTS</span></code></a> setting, which should be a list of compiled regular expression objects.</p> </li> <li><p class="first">Performs URL rewriting based on the <a class="reference internal" href="../settings/#std:setting-APPEND_SLASH"><code class="xref std std-setting docutils literal notranslate"><span class="pre">APPEND_SLASH</span></code></a> and <a class="reference internal" href="../settings/#std:setting-PREPEND_WWW"><code class="xref std std-setting docutils literal notranslate"><span class="pre">PREPEND_WWW</span></code></a> settings.</p> <p>If <a class="reference internal" href="../settings/#std:setting-APPEND_SLASH"><code class="xref std std-setting docutils literal notranslate"><span class="pre">APPEND_SLASH</span></code></a> is <code class="docutils literal notranslate"><span class="pre">True</span></code> and the initial URL doesn’t end with a slash, and it is not found in the URLconf, then a new URL is formed by appending a slash at the end. If this new URL is found in the URLconf, then Django redirects the request to this new URL. Otherwise, the initial URL is processed as usual.</p> <p>For example, <code class="docutils literal notranslate"><span class="pre">foo.com/bar</span></code> will be redirected to <code class="docutils literal notranslate"><span class="pre">foo.com/bar/</span></code> if you don’t have a valid URL pattern for <code class="docutils literal notranslate"><span class="pre">foo.com/bar</span></code> but <em>do</em> have a valid pattern for <code class="docutils literal notranslate"><span class="pre">foo.com/bar/</span></code>.</p> <p>If <a class="reference internal" href="../settings/#std:setting-PREPEND_WWW"><code class="xref std std-setting docutils literal notranslate"><span class="pre">PREPEND_WWW</span></code></a> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, URLs that lack a leading “www.” will be redirected to the same URL with a leading “www.”</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 class="docutils literal notranslate"><span class="pre">foo.com/bar</span></code> is distinct from <code class="docutils literal notranslate"><span class="pre">foo.com/bar/</span></code> – a search-engine indexer would treat them as separate URLs – so it’s best practice to normalize URLs.</p> </li> <li><p class="first">Sets the <code class="docutils literal notranslate"><span class="pre">Content-Length</span></code> header for non-streaming responses.</p> </li> </ul> <dl class="attribute"> <dt id="django.middleware.common.CommonMiddleware.response_redirect_class"> <code class="descclassname">CommonMiddleware.</code><code class="descname">response_redirect_class</code><a class="headerlink" href="#django.middleware.common.CommonMiddleware.response_redirect_class" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>Defaults to <a class="reference internal" href="../request-response/#django.http.HttpResponsePermanentRedirect" title="django.http.HttpResponsePermanentRedirect"><code class="xref py py-class docutils literal notranslate"><span class="pre">HttpResponsePermanentRedirect</span></code></a>. Subclass <code class="docutils literal notranslate"><span class="pre">CommonMiddleware</span></code> and override the attribute to customize the redirects issued by the middleware.</p> <dl class="class"> <dt id="django.middleware.common.BrokenLinkEmailsMiddleware"> <em class="property">class </em><code class="descname">BrokenLinkEmailsMiddleware</code><a class="headerlink" href="#django.middleware.common.BrokenLinkEmailsMiddleware" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <ul class="simple"> <li>Sends broken link notification emails to <a class="reference internal" href="../settings/#std:setting-MANAGERS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">MANAGERS</span></code></a> (see <a class="reference internal" href="../../howto/error-reporting/"><span class="doc">Error reporting</span></a>).</li> </ul> </div> <div class="section" id="s-module-django.middleware.gzip"> <span id="s-gzip-middleware"></span><span id="module-django.middleware.gzip"></span><span id="gzip-middleware"></span><h3>GZip middleware<a class="headerlink" href="#module-django.middleware.gzip" title="Permalink to this headline">¶</a></h3> <dl class="class"> <dt id="django.middleware.gzip.GZipMiddleware"> <em class="property">class </em><code class="descname">GZipMiddleware</code><a class="headerlink" href="#django.middleware.gzip.GZipMiddleware" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <div class="admonition warning"> <p class="first admonition-title">Warning</p> <p class="last">Security researchers recently revealed that when compression techniques (including <code class="docutils literal notranslate"><span class="pre">GZipMiddleware</span></code>) are used on a website, the site may become exposed to a number of possible attacks. Before using <code class="docutils literal notranslate"><span class="pre">GZipMiddleware</span></code> on your site, you should consider very carefully whether you are subject to these attacks. If you’re in <em>any</em> doubt about whether you’re affected, you should avoid using <code class="docutils literal notranslate"><span class="pre">GZipMiddleware</span></code>. For more details, see the <a class="reference external" href="http://breachattack.com/resources/BREACH%20-%20SSL,%20gone%20in%2030%20seconds.pdf">the BREACH paper (PDF)</a> and <a class="reference external" href="http://breachattack.com">breachattack.com</a>.</p> </div> <p>The <code class="docutils literal notranslate"><span class="pre">django.middleware.gzip.GZipMiddleware</span></code> compresses content for browsers that understand GZip compression (all modern browsers).</p> <p>This middleware should be placed before any other middleware that need to read or write the response body so that compression happens afterward.</p> <p>It will NOT compress content if any of the following are true:</p> <ul class="simple"> <li>The content body is less than 200 bytes long.</li> <li>The response has already set the <code class="docutils literal notranslate"><span class="pre">Content-Encoding</span></code> header.</li> <li>The request (the browser) hasn’t sent an <code class="docutils literal notranslate"><span class="pre">Accept-Encoding</span></code> header containing <code class="docutils literal notranslate"><span class="pre">gzip</span></code>.</li> </ul> <p>If the response has an <code class="docutils literal notranslate"><span class="pre">ETag</span></code> header, the ETag is made weak to comply with <span class="target" id="index-0"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc7232.html#section-2.1"><strong>RFC 7232#section-2.1</strong></a>.</p> <p>You can apply GZip compression to individual views using the <a class="reference internal" href="../../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"><span class="pre">gzip_page()</span></code></a> decorator.</p> </div> <div class="section" id="s-module-django.middleware.http"> <span id="s-conditional-get-middleware"></span><span id="module-django.middleware.http"></span><span id="conditional-get-middleware"></span><h3>Conditional GET middleware<a class="headerlink" href="#module-django.middleware.http" title="Permalink to this headline">¶</a></h3> <dl class="class"> <dt id="django.middleware.http.ConditionalGetMiddleware"> <em class="property">class </em><code class="descname">ConditionalGetMiddleware</code><a class="headerlink" href="#django.middleware.http.ConditionalGetMiddleware" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>Handles conditional GET operations. If the response doesn’t have an <code class="docutils literal notranslate"><span class="pre">ETag</span></code> header, the middleware adds one if needed. If the response has an <code class="docutils literal notranslate"><span class="pre">ETag</span></code> or <code class="docutils literal notranslate"><span class="pre">Last-Modified</span></code> header, and the request has <code class="docutils literal notranslate"><span class="pre">If-None-Match</span></code> or <code class="docutils literal notranslate"><span class="pre">If-Modified-Since</span></code>, the response is replaced by an <a class="reference internal" href="../request-response/#django.http.HttpResponseNotModified" title="django.http.HttpResponseNotModified"><code class="xref py py-class docutils literal notranslate"><span class="pre">HttpResponseNotModified</span></code></a>.</p> </div> <div class="section" id="s-module-django.middleware.locale"> <span id="s-locale-middleware"></span><span id="module-django.middleware.locale"></span><span id="locale-middleware"></span><h3>Locale middleware<a class="headerlink" href="#module-django.middleware.locale" title="Permalink to this headline">¶</a></h3> <dl class="class"> <dt id="django.middleware.locale.LocaleMiddleware"> <em class="property">class </em><code class="descname">LocaleMiddleware</code><a class="headerlink" href="#django.middleware.locale.LocaleMiddleware" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>Enables language selection based on data from the request. It customizes content for each user. See the <a class="reference internal" href="../../topics/i18n/translation/"><span class="doc">internationalization documentation</span></a>.</p> <dl class="attribute"> <dt id="django.middleware.locale.LocaleMiddleware.response_redirect_class"> <code class="descclassname">LocaleMiddleware.</code><code class="descname">response_redirect_class</code><a class="headerlink" href="#django.middleware.locale.LocaleMiddleware.response_redirect_class" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>Defaults to <a class="reference internal" href="../request-response/#django.http.HttpResponseRedirect" title="django.http.HttpResponseRedirect"><code class="xref py py-class docutils literal notranslate"><span class="pre">HttpResponseRedirect</span></code></a>. Subclass <code class="docutils literal notranslate"><span class="pre">LocaleMiddleware</span></code> and override the attribute to customize the redirects issued by the middleware.</p> </div> <div class="section" id="s-module-django.contrib.messages.middleware"> <span id="s-message-middleware"></span><span id="module-django.contrib.messages.middleware"></span><span id="message-middleware"></span><h3>Message middleware<a class="headerlink" href="#module-django.contrib.messages.middleware" title="Permalink to this headline">¶</a></h3> <dl class="class"> <dt id="django.contrib.messages.middleware.MessageMiddleware"> <em class="property">class </em><code class="descname">MessageMiddleware</code><a class="reference internal" href="../../_modules/django/contrib/messages/middleware/#MessageMiddleware"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.contrib.messages.middleware.MessageMiddleware" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>Enables cookie- and session-based message support. See the <a class="reference internal" href="../contrib/messages/"><span class="doc">messages documentation</span></a>.</p> </div> <div class="section" id="s-module-django.middleware.security"> <span id="s-id1"></span><span id="s-security-middleware"></span><span id="module-django.middleware.security"></span><span id="id1"></span><span id="security-middleware"></span><h3>Security middleware<a class="headerlink" href="#module-django.middleware.security" title="Permalink to this headline">¶</a></h3> <div class="admonition warning"> <p class="first admonition-title">Warning</p> <p class="last">If your deployment situation allows, it’s usually a good idea to have your front-end Web server perform the functionality provided by the <code class="docutils literal notranslate"><span class="pre">SecurityMiddleware</span></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.</p> </div> <dl class="class"> <dt id="django.middleware.security.SecurityMiddleware"> <em class="property">class </em><code class="descname">SecurityMiddleware</code><a class="headerlink" href="#django.middleware.security.SecurityMiddleware" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>The <code class="docutils literal notranslate"><span class="pre">django.middleware.security.SecurityMiddleware</span></code> provides several security enhancements to the request/response cycle. Each one can be independently enabled or disabled with a setting.</p> <ul class="simple"> <li><a class="reference internal" href="../settings/#std:setting-SECURE_BROWSER_XSS_FILTER"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_BROWSER_XSS_FILTER</span></code></a></li> <li><a class="reference internal" href="../settings/#std:setting-SECURE_CONTENT_TYPE_NOSNIFF"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_CONTENT_TYPE_NOSNIFF</span></code></a></li> <li><a class="reference internal" href="../settings/#std:setting-SECURE_HSTS_INCLUDE_SUBDOMAINS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_HSTS_INCLUDE_SUBDOMAINS</span></code></a></li> <li><a class="reference internal" href="../settings/#std:setting-SECURE_HSTS_PRELOAD"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_HSTS_PRELOAD</span></code></a></li> <li><a class="reference internal" href="../settings/#std:setting-SECURE_HSTS_SECONDS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_HSTS_SECONDS</span></code></a></li> <li><a class="reference internal" href="../settings/#std:setting-SECURE_REDIRECT_EXEMPT"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_REDIRECT_EXEMPT</span></code></a></li> <li><a class="reference internal" href="../settings/#std:setting-SECURE_REFERRER_POLICY"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_REFERRER_POLICY</span></code></a></li> <li><a class="reference internal" href="../settings/#std:setting-SECURE_SSL_HOST"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_SSL_HOST</span></code></a></li> <li><a class="reference internal" href="../settings/#std:setting-SECURE_SSL_REDIRECT"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_SSL_REDIRECT</span></code></a></li> </ul> <div class="section" id="s-http-strict-transport-security"> <span id="s-id2"></span><span id="http-strict-transport-security"></span><span id="id2"></span><h4>HTTP Strict Transport Security<a class="headerlink" href="#http-strict-transport-security" title="Permalink to this headline">¶</a></h4> <p>For sites that should only be accessed over HTTPS, you can instruct modern browsers to refuse to connect to your domain name via an insecure connection (for a given period of time) by setting the <a class="reference external" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security">“Strict-Transport-Security” header</a>. This reduces your exposure to some SSL-stripping man-in-the-middle (MITM) attacks.</p> <p><code class="docutils literal notranslate"><span class="pre">SecurityMiddleware</span></code> will set this header for you on all HTTPS responses if you set the <a class="reference internal" href="../settings/#std:setting-SECURE_HSTS_SECONDS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_HSTS_SECONDS</span></code></a> setting to a non-zero integer value.</p> <p>When enabling HSTS, it’s a good idea to first use a small value for testing, for example, <a class="reference internal" href="../settings/#std:setting-SECURE_HSTS_SECONDS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_HSTS_SECONDS</span> <span class="pre">=</span> <span class="pre">3600</span></code></a> 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).</p> <p>Additionally, if you set the <a class="reference internal" href="../settings/#std:setting-SECURE_HSTS_INCLUDE_SUBDOMAINS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_HSTS_INCLUDE_SUBDOMAINS</span></code></a> setting to <code class="docutils literal notranslate"><span class="pre">True</span></code>, <code class="docutils literal notranslate"><span class="pre">SecurityMiddleware</span></code> will add the <code class="docutils literal notranslate"><span class="pre">includeSubDomains</span></code> directive to the <code class="docutils literal notranslate"><span class="pre">Strict-Transport-Security</span></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.</p> <p>If you wish to submit your site to the <a class="reference external" href="https://hstspreload.org/">browser preload list</a>, set the <a class="reference internal" href="../settings/#std:setting-SECURE_HSTS_PRELOAD"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_HSTS_PRELOAD</span></code></a> setting to <code class="docutils literal notranslate"><span class="pre">True</span></code>. That appends the <code class="docutils literal notranslate"><span class="pre">preload</span></code> directive to the <code class="docutils literal notranslate"><span class="pre">Strict-Transport-Security</span></code> header.</p> <div class="admonition warning"> <p class="first admonition-title">Warning</p> <p>The HSTS policy applies to your entire domain, not just the URL of the response that you set the header on. Therefore, you should only use it if your entire domain is served via HTTPS only.</p> <p class="last">Browsers properly respecting the HSTS header will refuse to allow users to 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!</p> </div> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">If you are deployed behind a load-balancer or reverse-proxy server, and the <code class="docutils literal notranslate"><span class="pre">Strict-Transport-Security</span></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 <a class="reference internal" href="../settings/#std:setting-SECURE_PROXY_SSL_HEADER"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_PROXY_SSL_HEADER</span></code></a> setting.</p> </div> </div> <div class="section" id="s-referrer-policy"> <span id="s-id4"></span><span id="referrer-policy"></span><span id="id4"></span><h4>Referrer Policy<a class="headerlink" href="#referrer-policy" title="Permalink to this headline">¶</a></h4> <div class="versionadded"> <span class="title">New in Django 3.0.</span> </div> <p>Browsers use <a class="reference external" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referer">the Referer header</a> as a way to send information to a site 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.</p> <p>Some browsers have the ability to accept hints about whether they should send the HTTP <code class="docutils literal notranslate"><span class="pre">Referer</span></code> header when a user clicks a link; this hint is provided via <a class="reference external" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy">the Referrer-Policy header</a>. This header can suggest any of three behaviors to browsers:</p> <ul class="simple"> <li>Full URL: send the entire URL in the <code class="docutils literal notranslate"><span class="pre">Referer</span></code> header. For example, if the user is visiting <code class="docutils literal notranslate"><span class="pre">https://example.com/page.html</span></code>, the <code class="docutils literal notranslate"><span class="pre">Referer</span></code> header would contain <code class="docutils literal notranslate"><span class="pre">&quot;https://example.com/page.html&quot;</span></code>.</li> <li>Origin only: send only the “origin” in the referrer. The origin consists of the scheme, host and (optionally) port number. For example, if the user is visiting <code class="docutils literal notranslate"><span class="pre">https://example.com/page.html</span></code>, the origin would be <code class="docutils literal notranslate"><span class="pre">https://example.com/</span></code>.</li> <li>No referrer: do not send a <code class="docutils literal notranslate"><span class="pre">Referer</span></code> header at all.</li> </ul> <p>There are two types of conditions this header can tell a browser to watch out for:</p> <ul class="simple"> <li>Same-origin versus cross-origin: a link from <code class="docutils literal notranslate"><span class="pre">https://example.com/1.html</span></code> to <code class="docutils literal notranslate"><span class="pre">https://example.com/2.html</span></code> is same-origin. A link from <code class="docutils literal notranslate"><span class="pre">https://example.com/page.html</span></code> to <code class="docutils literal notranslate"><span class="pre">https://not.example.com/page.html</span></code> is cross-origin.</li> <li>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.</li> </ul> <div class="admonition warning"> <p class="first admonition-title">Warning</p> <p class="last">When your site is served via HTTPS, <a class="reference internal" href="../csrf/#using-csrf"><span class="std std-ref">Django’s CSRF protection system</span></a> requires the <code class="docutils literal notranslate"><span class="pre">Referer</span></code> header to be present, so completely disabling the <code class="docutils literal notranslate"><span class="pre">Referer</span></code> header will interfere with CSRF protection. To gain most of the benefits of disabling <code class="docutils literal notranslate"><span class="pre">Referer</span></code> headers while also keeping CSRF protection, consider enabling only same-origin referrers.</p> </div> <p><code class="docutils literal notranslate"><span class="pre">SecurityMiddleware</span></code> can set the <code class="docutils literal notranslate"><span class="pre">Referrer-Policy</span></code> header for you, based on the the <a class="reference internal" href="../settings/#std:setting-SECURE_REFERRER_POLICY"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_REFERRER_POLICY</span></code></a> setting (note spelling: browsers send a <code class="docutils literal notranslate"><span class="pre">Referer</span></code> header when a user clicks a link, but the header instructing a browser whether to do so is spelled <code class="docutils literal notranslate"><span class="pre">Referrer-Policy</span></code>). The valid values for this setting are:</p> <dl class="docutils"> <dt><code class="docutils literal notranslate"><span class="pre">no-referrer</span></code></dt> <dd>Instructs the browser to send no referrer for links clicked on this site.</dd> <dt><code class="docutils literal notranslate"><span class="pre">no-referrer-when-downgrade</span></code></dt> <dd>Instructs the browser to send a full URL as the referrer, but only when no protocol downgrade occurs.</dd> <dt><code class="docutils literal notranslate"><span class="pre">origin</span></code></dt> <dd>Instructs the browser to send only the origin, not the full URL, as the referrer.</dd> <dt><code class="docutils literal notranslate"><span class="pre">origin-when-cross-origin</span></code></dt> <dd>Instructs the browser to send the full URL as the referrer for same-origin links, and only the origin for cross-origin links.</dd> <dt><code class="docutils literal notranslate"><span class="pre">same-origin</span></code></dt> <dd>Instructs the browser to send a full URL, but only for same-origin links. No referrer will be sent for cross-origin links.</dd> <dt><code class="docutils literal notranslate"><span class="pre">strict-origin</span></code></dt> <dd>Instructs the browser to send only the origin, not the full URL, and to send no referrer when a protocol downgrade occurs.</dd> <dt><code class="docutils literal notranslate"><span class="pre">strict-origin-when-cross-origin</span></code></dt> <dd>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.</dd> <dt><code class="docutils literal notranslate"><span class="pre">unsafe-url</span></code></dt> <dd>Instructs the browser to always send the full URL as the referrer.</dd> </dl> <div class="admonition-unknown-policy-values admonition"> <p class="first admonition-title">Unknown Policy Values</p> <p class="last">Where a policy value is <a class="reference external" href="https://w3c.github.io/webappsec-referrer-policy/#unknown-policy-values">unknown</a> by a user agent, it is possible to 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 <a class="reference internal" href="../settings/#std:setting-SECURE_REFERRER_POLICY"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_REFERRER_POLICY</span></code></a>.</p> </div> </div> <div class="section" id="s-x-content-type-options-nosniff"> <span id="s-x-content-type-options"></span><span id="x-content-type-options-nosniff"></span><span id="x-content-type-options"></span><h4><code class="docutils literal notranslate"><span class="pre">X-Content-Type-Options:</span> <span class="pre">nosniff</span></code><a class="headerlink" href="#x-content-type-options-nosniff" title="Permalink to this headline">¶</a></h4> <p>Some browsers will try to guess the content types of the assets that they fetch, overriding the <code class="docutils literal notranslate"><span class="pre">Content-Type</span></code> header. While this can help display sites with improperly configured servers, it can also pose a security risk.</p> <p>If your site serves user-uploaded files, a malicious user could upload a specially-crafted file that would be interpreted as HTML or JavaScript by the browser when you expected it to be something harmless.</p> <p>To prevent the browser from guessing the content type and force it to always use the type provided in the <code class="docutils literal notranslate"><span class="pre">Content-Type</span></code> header, you can pass the <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> header. <code class="docutils literal notranslate"><span class="pre">SecurityMiddleware</span></code> will do this for all responses if the <a class="reference internal" href="../settings/#std:setting-SECURE_CONTENT_TYPE_NOSNIFF"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_CONTENT_TYPE_NOSNIFF</span></code></a> setting is <code class="docutils literal notranslate"><span class="pre">True</span></code>.</p> <p>Note that in most deployment situations where Django isn’t involved in serving user-uploaded files, this setting won’t help you. For example, if your <a class="reference internal" href="../settings/#std:setting-MEDIA_URL"><code class="xref std std-setting docutils literal notranslate"><span class="pre">MEDIA_URL</span></code></a> 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.</p> </div> <div class="section" id="s-x-xss-protection-1-mode-block"> <span id="s-x-xss-protection"></span><span id="x-xss-protection-1-mode-block"></span><span id="x-xss-protection"></span><h4><code class="docutils literal notranslate"><span class="pre">X-XSS-Protection:</span> <span class="pre">1;</span> <span class="pre">mode=block</span></code><a class="headerlink" href="#x-xss-protection-1-mode-block" title="Permalink to this headline">¶</a></h4> <p>Some browsers have the ability to block content that appears to be an <a class="reference external" href="https://en.wikipedia.org/wiki/Cross-site_scripting">XSS attack</a>. 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.</p> <p>The <a class="reference external" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection">X-XSS-Protection header</a> is used to control the operation of the XSS filter.</p> <p>To enable the XSS filter in the browser, and force it to always block suspected XSS attacks, you can pass the <code class="docutils literal notranslate"><span class="pre">X-XSS-Protection:</span> <span class="pre">1;</span> <span class="pre">mode=block</span></code> header. <code class="docutils literal notranslate"><span class="pre">SecurityMiddleware</span></code> will do this for all responses if the <a class="reference internal" href="../settings/#std:setting-SECURE_BROWSER_XSS_FILTER"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_BROWSER_XSS_FILTER</span></code></a> setting is <code class="docutils literal notranslate"><span class="pre">True</span></code>.</p> <div class="admonition warning"> <p class="first admonition-title">Warning</p> <p class="last">The browser XSS filter is a useful defense measure, but must not be relied upon exclusively. It cannot detect all XSS attacks and not all browsers support the header. Ensure you are still <a class="reference internal" href="../../topics/security/#cross-site-scripting"><span class="std std-ref">validating and sanitizing</span></a> all input to prevent XSS attacks.</p> </div> </div> <div class="section" id="s-ssl-redirect"> <span id="s-id10"></span><span id="ssl-redirect"></span><span id="id10"></span><h4>SSL Redirect<a class="headerlink" href="#ssl-redirect" title="Permalink to this headline">¶</a></h4> <p>If your site offers both HTTP and HTTPS connections, most users will end up with an unsecured connection by default. For best security, you should redirect all HTTP connections to HTTPS.</p> <p>If you set the <a class="reference internal" href="../settings/#std:setting-SECURE_SSL_REDIRECT"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_SSL_REDIRECT</span></code></a> setting to True, <code class="docutils literal notranslate"><span class="pre">SecurityMiddleware</span></code> will permanently (HTTP 301) redirect all HTTP connections to HTTPS.</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">For performance reasons, it’s preferable to do these redirects outside of Django, in a front-end load balancer or reverse-proxy server such as <a class="reference external" href="https://nginx.org">nginx</a>. <a class="reference internal" href="../settings/#std:setting-SECURE_SSL_REDIRECT"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_SSL_REDIRECT</span></code></a> is intended for the deployment situations where this isn’t an option.</p> </div> <p>If the <a class="reference internal" href="../settings/#std:setting-SECURE_SSL_HOST"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_SSL_HOST</span></code></a> setting has a value, all redirects will be sent to that host instead of the originally-requested host.</p> <p>If there are a few pages on your site that should be available over HTTP, and not redirected to HTTPS, you can list regular expressions to match those URLs in the <a class="reference internal" href="../settings/#std:setting-SECURE_REDIRECT_EXEMPT"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_REDIRECT_EXEMPT</span></code></a> setting.</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">If you are deployed behind a load-balancer or reverse-proxy server and Django can’t seem to tell when a request actually is already secure, you may need to set the <a class="reference internal" href="../settings/#std:setting-SECURE_PROXY_SSL_HEADER"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECURE_PROXY_SSL_HEADER</span></code></a> setting.</p> </div> </div> </div> <div class="section" id="s-module-django.contrib.sessions.middleware"> <span id="s-session-middleware"></span><span id="module-django.contrib.sessions.middleware"></span><span id="session-middleware"></span><h3>Session middleware<a class="headerlink" href="#module-django.contrib.sessions.middleware" title="Permalink to this headline">¶</a></h3> <dl class="class"> <dt id="django.contrib.sessions.middleware.SessionMiddleware"> <em class="property">class </em><code class="descname">SessionMiddleware</code><a class="headerlink" href="#django.contrib.sessions.middleware.SessionMiddleware" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>Enables session support. See the <a class="reference internal" href="../../topics/http/sessions/"><span class="doc">session documentation</span></a>.</p> </div> <div class="section" id="s-module-django.contrib.sites.middleware"> <span id="s-site-middleware"></span><span id="module-django.contrib.sites.middleware"></span><span id="site-middleware"></span><h3>Site middleware<a class="headerlink" href="#module-django.contrib.sites.middleware" title="Permalink to this headline">¶</a></h3> <dl class="class"> <dt id="django.contrib.sites.middleware.CurrentSiteMiddleware"> <em class="property">class </em><code class="descname">CurrentSiteMiddleware</code><a class="reference internal" href="../../_modules/django/contrib/sites/middleware/#CurrentSiteMiddleware"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.contrib.sites.middleware.CurrentSiteMiddleware" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>Adds the <code class="docutils literal notranslate"><span class="pre">site</span></code> attribute representing the current site to every incoming <code class="docutils literal notranslate"><span class="pre">HttpRequest</span></code> object. See the <a class="reference internal" href="../contrib/sites/#site-middleware"><span class="std std-ref">sites documentation</span></a>.</p> </div> <div class="section" id="s-module-django.contrib.auth.middleware"> <span id="s-authentication-middleware"></span><span id="module-django.contrib.auth.middleware"></span><span id="authentication-middleware"></span><h3>Authentication middleware<a class="headerlink" href="#module-django.contrib.auth.middleware" title="Permalink to this headline">¶</a></h3> <dl class="class"> <dt id="django.contrib.auth.middleware.AuthenticationMiddleware"> <em class="property">class </em><code class="descname">AuthenticationMiddleware</code><a class="headerlink" href="#django.contrib.auth.middleware.AuthenticationMiddleware" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>Adds the <code class="docutils literal notranslate"><span class="pre">user</span></code> attribute, representing the currently-logged-in user, to every incoming <code class="docutils literal notranslate"><span class="pre">HttpRequest</span></code> object. See <a class="reference internal" href="../../topics/auth/default/#auth-web-requests"><span class="std std-ref">Authentication in Web requests</span></a>.</p> <dl class="class"> <dt id="django.contrib.auth.middleware.RemoteUserMiddleware"> <em class="property">class </em><code class="descname">RemoteUserMiddleware</code><a class="headerlink" href="#django.contrib.auth.middleware.RemoteUserMiddleware" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>Middleware for utilizing Web server provided authentication. See <a class="reference internal" href="../../howto/auth-remote-user/"><span class="doc">Authentication using REMOTE_USER</span></a> for usage details.</p> <dl class="class"> <dt id="django.contrib.auth.middleware.PersistentRemoteUserMiddleware"> <em class="property">class </em><code class="descname">PersistentRemoteUserMiddleware</code><a class="headerlink" href="#django.contrib.auth.middleware.PersistentRemoteUserMiddleware" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>Middleware for utilizing Web server provided authentication when enabled only on the login page. See <a class="reference internal" href="../../howto/auth-remote-user/#persistent-remote-user-middleware-howto"><span class="std std-ref">Using REMOTE_USER on login pages only</span></a> for usage details.</p> </div> <div class="section" id="s-csrf-protection-middleware"> <span id="csrf-protection-middleware"></span><h3>CSRF protection middleware<a class="headerlink" href="#csrf-protection-middleware" title="Permalink to this headline">¶</a></h3> <dl class="class"> <dt id="django.middleware.csrf.CsrfViewMiddleware"> <em class="property">class </em><code class="descname">CsrfViewMiddleware</code><a class="headerlink" href="#django.middleware.csrf.CsrfViewMiddleware" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>Adds protection against Cross Site Request Forgeries by adding hidden form fields to POST forms and checking requests for the correct value. See the <a class="reference internal" href="../csrf/"><span class="doc">Cross Site Request Forgery protection documentation</span></a>.</p> </div> <div class="section" id="s-x-frame-options-middleware"> <span id="x-frame-options-middleware"></span><h3><code class="docutils literal notranslate"><span class="pre">X-Frame-Options</span></code> middleware<a class="headerlink" href="#x-frame-options-middleware" title="Permalink to this headline">¶</a></h3> <dl class="class"> <dt id="django.middleware.clickjacking.XFrameOptionsMiddleware"> <em class="property">class </em><code class="descname">XFrameOptionsMiddleware</code><a class="reference internal" href="../../_modules/django/middleware/clickjacking/#XFrameOptionsMiddleware"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.middleware.clickjacking.XFrameOptionsMiddleware" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>Simple <a class="reference internal" href="../clickjacking/"><span class="doc">clickjacking protection via the X-Frame-Options header</span></a>.</p> </div> </div> <div class="section" id="s-middleware-ordering"> <span id="s-id11"></span><span id="middleware-ordering"></span><span id="id11"></span><h2>Middleware ordering<a class="headerlink" href="#middleware-ordering" title="Permalink to this headline">¶</a></h2> <p>Here are some hints about the ordering of various Django middleware classes:</p> <ol class="arabic"> <li><p class="first"><a class="reference internal" href="#django.middleware.security.SecurityMiddleware" title="django.middleware.security.SecurityMiddleware"><code class="xref py py-class docutils literal notranslate"><span class="pre">SecurityMiddleware</span></code></a></p> <p>It should go near the top of the list if you’re going to turn on the SSL redirect as that avoids running through a bunch of other unnecessary middleware.</p> </li> <li><p class="first"><a class="reference internal" href="#django.middleware.cache.UpdateCacheMiddleware" title="django.middleware.cache.UpdateCacheMiddleware"><code class="xref py py-class docutils literal notranslate"><span class="pre">UpdateCacheMiddleware</span></code></a></p> <p>Before those that modify the <code class="docutils literal notranslate"><span class="pre">Vary</span></code> header (<code class="docutils literal notranslate"><span class="pre">SessionMiddleware</span></code>, <code class="docutils literal notranslate"><span class="pre">GZipMiddleware</span></code>, <code class="docutils literal notranslate"><span class="pre">LocaleMiddleware</span></code>).</p> </li> <li><p class="first"><a class="reference internal" href="#django.middleware.gzip.GZipMiddleware" title="django.middleware.gzip.GZipMiddleware"><code class="xref py py-class docutils literal notranslate"><span class="pre">GZipMiddleware</span></code></a></p> <p>Before any middleware that may change or use the response body.</p> <p>After <code class="docutils literal notranslate"><span class="pre">UpdateCacheMiddleware</span></code>: Modifies <code class="docutils literal notranslate"><span class="pre">Vary</span></code> header.</p> </li> <li><p class="first"><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"><span class="pre">SessionMiddleware</span></code></a></p> <p>Before any middleware that may raise an an exception to trigger an error view (such as <a class="reference internal" href="../exceptions/#django.core.exceptions.PermissionDenied" title="django.core.exceptions.PermissionDenied"><code class="xref py py-exc docutils literal notranslate"><span class="pre">PermissionDenied</span></code></a>) if you’re using <a class="reference internal" href="../settings/#std:setting-CSRF_USE_SESSIONS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CSRF_USE_SESSIONS</span></code></a>.</p> <p>After <code class="docutils literal notranslate"><span class="pre">UpdateCacheMiddleware</span></code>: Modifies <code class="docutils literal notranslate"><span class="pre">Vary</span></code> header.</p> </li> <li><p class="first"><a class="reference internal" href="#django.middleware.http.ConditionalGetMiddleware" title="django.middleware.http.ConditionalGetMiddleware"><code class="xref py py-class docutils literal notranslate"><span class="pre">ConditionalGetMiddleware</span></code></a></p> <p>Before any middleware that may change the response (it sets the <code class="docutils literal notranslate"><span class="pre">ETag</span></code> header).</p> <p>After <code class="docutils literal notranslate"><span class="pre">GZipMiddleware</span></code> so it won’t calculate an <code class="docutils literal notranslate"><span class="pre">ETag</span></code> header on gzipped contents.</p> </li> <li><p class="first"><a class="reference internal" href="#django.middleware.locale.LocaleMiddleware" title="django.middleware.locale.LocaleMiddleware"><code class="xref py py-class docutils literal notranslate"><span class="pre">LocaleMiddleware</span></code></a></p> <p>One of the topmost, after <code class="docutils literal notranslate"><span class="pre">SessionMiddleware</span></code> (uses session data) and <code class="docutils literal notranslate"><span class="pre">UpdateCacheMiddleware</span></code> (modifies <code class="docutils literal notranslate"><span class="pre">Vary</span></code> header).</p> </li> <li><p class="first"><a class="reference internal" href="#django.middleware.common.CommonMiddleware" title="django.middleware.common.CommonMiddleware"><code class="xref py py-class docutils literal notranslate"><span class="pre">CommonMiddleware</span></code></a></p> <p>Before any middleware that may change the response (it sets the <code class="docutils literal notranslate"><span class="pre">Content-Length</span></code> header). A middleware that appears before <code class="docutils literal notranslate"><span class="pre">CommonMiddleware</span></code> and changes the response must reset <code class="docutils literal notranslate"><span class="pre">Content-Length</span></code>.</p> <p>Close to the top: it redirects when <a class="reference internal" href="../settings/#std:setting-APPEND_SLASH"><code class="xref std std-setting docutils literal notranslate"><span class="pre">APPEND_SLASH</span></code></a> or <a class="reference internal" href="../settings/#std:setting-PREPEND_WWW"><code class="xref std std-setting docutils literal notranslate"><span class="pre">PREPEND_WWW</span></code></a> are set to <code class="docutils literal notranslate"><span class="pre">True</span></code>.</p> <p>After <code class="docutils literal notranslate"><span class="pre">SessionMiddleware</span></code> if you’re using <a class="reference internal" href="../settings/#std:setting-CSRF_USE_SESSIONS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CSRF_USE_SESSIONS</span></code></a>.</p> </li> <li><p class="first"><a class="reference internal" href="#django.middleware.csrf.CsrfViewMiddleware" title="django.middleware.csrf.CsrfViewMiddleware"><code class="xref py py-class docutils literal notranslate"><span class="pre">CsrfViewMiddleware</span></code></a></p> <p>Before any view middleware that assumes that CSRF attacks have been dealt with.</p> <p>Before <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"><span class="pre">RemoteUserMiddleware</span></code></a>, or any other authentication middleware that may perform a login, and hence rotate the CSRF token, before calling down the middleware chain.</p> <p>After <code class="docutils literal notranslate"><span class="pre">SessionMiddleware</span></code> if you’re using <a class="reference internal" href="../settings/#std:setting-CSRF_USE_SESSIONS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CSRF_USE_SESSIONS</span></code></a>.</p> </li> <li><p class="first"><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"><span class="pre">AuthenticationMiddleware</span></code></a></p> <p>After <code class="docutils literal notranslate"><span class="pre">SessionMiddleware</span></code>: uses session storage.</p> </li> <li><p class="first"><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"><span class="pre">MessageMiddleware</span></code></a></p> <p>After <code class="docutils literal notranslate"><span class="pre">SessionMiddleware</span></code>: can use session-based storage.</p> </li> <li><p class="first"><a class="reference internal" href="#django.middleware.cache.FetchFromCacheMiddleware" title="django.middleware.cache.FetchFromCacheMiddleware"><code class="xref py py-class docutils literal notranslate"><span class="pre">FetchFromCacheMiddleware</span></code></a></p> <p>After any middleware that modifies the <code class="docutils literal notranslate"><span class="pre">Vary</span></code> header: that header is used to pick a value for the cache hash-key.</p> </li> <li><p class="first"><a class="reference internal" href="../contrib/flatpages/#django.contrib.flatpages.middleware.FlatpageFallbackMiddleware" title="django.contrib.flatpages.middleware.FlatpageFallbackMiddleware"><code class="xref py py-class docutils literal notranslate"><span class="pre">FlatpageFallbackMiddleware</span></code></a></p> <p>Should be near the bottom as it’s a last-resort type of middleware.</p> </li> <li><p class="first"><a class="reference internal" href="../contrib/redirects/#django.contrib.redirects.middleware.RedirectFallbackMiddleware" title="django.contrib.redirects.middleware.RedirectFallbackMiddleware"><code class="xref py py-class docutils literal notranslate"><span class="pre">RedirectFallbackMiddleware</span></code></a></p> <p>Should be near the bottom as it’s a last-resort type of middleware.</p> </li> </ol> </div> </div> </div> <div class="browse-horizontal"> <div class="left"><a rel="prev" href="../forms/validation/"><i class="icon icon-chevron-left"></i> Form and field validation</a></div> <div class="right"><a rel="next" href="../migration-operations/">Migration Operations <i class="icon icon-chevron-right"></i></a></div> </div> <a href="#top" class="backtotop"><i class="icon icon-chevron-up"></i> Back to Top</a> </div> <h1 class="visuallyhidden">Additional Information</h1> <div role="complementary"> <div class="fundraising-sidebar"> <h2>Support Django!</h2> <div class="small-heart"> <img src="https://static.djangoproject.com/img/fundraising-heart.cd6bb84ffd33.svg" alt="Support Django!" /> </div> <div class="small-cta"> <ul class="list-links-small"> <li><a href="https://www.djangoproject.com/fundraising/"> Adam Bogdał donated to the Django Software Foundation to support Django development. Donate today! </a></li> </ul> </div> </div> <h2>Contents</h2> <ul> <li><a class="reference internal" href="#">Middleware</a><ul> <li><a class="reference internal" href="#available-middleware">Available middleware</a><ul> <li><a class="reference internal" href="#module-django.middleware.cache">Cache middleware</a></li> <li><a class="reference internal" href="#module-django.middleware.common">“Common” middleware</a></li> <li><a class="reference internal" href="#module-django.middleware.gzip">GZip middleware</a></li> <li><a class="reference internal" href="#module-django.middleware.http">Conditional GET middleware</a></li> <li><a class="reference internal" href="#module-django.middleware.locale">Locale middleware</a></li> <li><a class="reference internal" href="#module-django.contrib.messages.middleware">Message middleware</a></li> <li><a class="reference internal" href="#module-django.middleware.security">Security middleware</a><ul> <li><a class="reference internal" href="#http-strict-transport-security">HTTP Strict Transport Security</a></li> <li><a class="reference internal" href="#referrer-policy">Referrer Policy</a></li> <li><a class="reference internal" href="#x-content-type-options-nosniff"><code class="docutils literal notranslate"><span class="pre">X-Content-Type-Options:</span> <span class="pre">nosniff</span></code></a></li> <li><a class="reference internal" href="#x-xss-protection-1-mode-block"><code class="docutils literal notranslate"><span class="pre">X-XSS-Protection:</span> <span class="pre">1;</span> <span class="pre">mode=block</span></code></a></li> <li><a class="reference internal" href="#ssl-redirect">SSL Redirect</a></li> </ul> </li> <li><a class="reference internal" href="#module-django.contrib.sessions.middleware">Session middleware</a></li> <li><a class="reference internal" href="#module-django.contrib.sites.middleware">Site middleware</a></li> <li><a class="reference internal" href="#module-django.contrib.auth.middleware">Authentication middleware</a></li> <li><a class="reference internal" href="#csrf-protection-middleware">CSRF protection middleware</a></li> <li><a class="reference internal" href="#x-frame-options-middleware"><code class="docutils literal notranslate"><span class="pre">X-Frame-Options</span></code> middleware</a></li> </ul> </li> <li><a class="reference internal" href="#middleware-ordering">Middleware ordering</a></li> </ul> </li> </ul> <h2>Browse</h2> <ul> <li>Prev: <a rel="prev" href="../forms/validation/">Form and field validation</a></li> <li>Next: <a rel="next" href="../migration-operations/">Migration Operations</a></li> <li><a href="https://docs.djangoproject.com/en/3.0/contents/">Table of contents</a></li> <li><a href="https://docs.djangoproject.com/en/3.0/genindex/">General Index</a></li> <li><a href="https://docs.djangoproject.com/en/3.0/py-modindex/">Python Module Index</a></li> </ul> <h2>You are here:</h2> <ul> <li> <a href="https://docs.djangoproject.com/en/3.0/">Django 3.0 documentation</a> <ul><li><a href="../">API Reference</a> <ul><li>Middleware</li></ul> </li></ul> </li> </ul> <h2 id="getting-help-sidebar">Getting help</h2> <dl class="list-links"> <dt><a href="https://docs.djangoproject.com/en/3.0/faq/">FAQ</a></dt> <dd>Try the FAQ — it's got answers to many common questions.</dd> <dt><a href="/en/stable/genindex/">Index</a>, <a href="/en/stable/py-modindex/">Module Index</a>, or <a href="/en/stable/contents/">Table of Contents</a></dt> <dd>Handy when looking for specific information.</dd> <dt><a href="https://groups.google.com/group/django-users/">django-users mailing list</a></dt> <dd>Search for information in the archives of the django-users mailing list, or post a question.</dd> <dt><a href="irc://irc.libera.chat/django">#django IRC channel</a></dt> <dd>Ask a question in the #django IRC channel, or search the IRC logs to see if it’s been asked before.</dd> <dt><a href="https://discord.gg/xcRH6mN4fa">Django Discord Server</a></dt> <dd>Join the Django Discord Community.</dd> <dt><a href="https://forum.djangoproject.com/">Official Django Forum</a></dt> <dd>Join the community on the Django Forum.</dd> <dt><a href="https://code.djangoproject.com/">Ticket tracker</a></dt> <dd>Report bugs with Django or Django documentation in our ticket tracker.</dd> </dl> <h2>Download:</h2> <p> Offline (Django 3.0): <a href="https://media.djangoproject.com/docs/django-docs-3.0-en.zip">HTML</a> | <a href="https://media.readthedocs.org/pdf/django/3.0.x/django.pdf">PDF</a> | <a href="https://media.readthedocs.org/epub/django/3.0.x/django.epub">ePub</a> <br> <span class="quiet"> Provided by <a href="https://readthedocs.org/">Read the Docs</a>. </span> </p> </div> </div> <!-- SVGs --> <svg xmlns="http://www.w3.org/2000/svg"> <symbol viewBox="0 0 24 24" id="icon-auto"><path d="M0 0h24v24H0z" fill="currentColor"/><path d="M12 22C6.477 22 2 17.523 2 12S6.477 2 12 2s10 4.477 10 10-4.477 10-10 10zm0-2V4a8 8 0 1 0 0 16z"/></symbol> <symbol viewBox="0 0 24 24" id="icon-moon"><path d="M0 0h24v24H0z" fill="currentColor"/><path d="M10 7a7 7 0 0 0 12 4.9v.1c0 5.523-4.477 10-10 10S2 17.523 2 12 6.477 2 12 2h.1A6.979 6.979 0 0 0 10 7zm-6 5a8 8 0 0 0 15.062 3.762A9 9 0 0 1 8.238 4.938 7.999 7.999 0 0 0 4 12z"/></symbol> <symbol viewBox="0 0 24 24" id="icon-sun"><path d="M0 0h24v24H0z" fill="currentColor"/><path d="M12 18a6 6 0 1 1 0-12 6 6 0 0 1 0 12zm0-2a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM11 1h2v3h-2V1zm0 19h2v3h-2v-3zM3.515 4.929l1.414-1.414L7.05 5.636 5.636 7.05 3.515 4.93zM16.95 18.364l1.414-1.414 2.121 2.121-1.414 1.414-2.121-2.121zm2.121-14.85l1.414 1.415-2.121 2.121-1.414-1.414 2.121-2.121zM5.636 16.95l1.414 1.414-2.121 2.121-1.414-1.414 2.121-2.121zM23 11v2h-3v-2h3zM4 11v2H1v-2h3z"/></symbol> </svg> <!-- END SVGs --> <div role="contentinfo"> <div class="subfooter"> <div class="container"> <h1 class="visuallyhidden">Django Links</h1> <div class="column-container"> <div class="col-learn-more"> <h2>Learn More</h2> <ul> <li><a href="https://www.djangoproject.com/start/overview/">About Django</a></li> <li><a href="https://www.djangoproject.com/start/">Getting Started with Django</a></li> <li><a href="https://docs.djangoproject.com/en/dev/internals/organization/">Team Organization</a></li> <li><a href="https://www.djangoproject.com/foundation/">Django Software Foundation</a></li> <li><a href="https://www.djangoproject.com/conduct/">Code of Conduct</a></li> <li><a href="https://www.djangoproject.com/diversity/">Diversity Statement</a></li> </ul> </div> <div class="col-get-involved"> <h2>Get Involved</h2> <ul> <li><a href="https://www.djangoproject.com/community/">Join a Group</a></li> <li><a href="https://docs.djangoproject.com/en/dev/internals/contributing/">Contribute to Django</a></li> <li><a href="https://docs.djangoproject.com/en/dev/internals/contributing/bugs-and-features/">Submit a Bug</a></li> <li><a href="https://docs.djangoproject.com/en/dev/internals/security/#reporting-security-issues">Report a Security Issue</a></li> <li><a href="https://www.djangoproject.com/foundation/individual-members/">Individual membership</a></li> </ul> </div> <div class="col-get-help"> <h2>Get Help</h2> <ul> <li><a href="https://docs.djangoproject.com/en/stable/faq/">Getting Help FAQ</a> </li> <li><a href="irc://irc.libera.chat/django">#django IRC channel</a></li> <li><a href="https://discord.gg/xcRH6mN4fa" target="_blank">Django Discord</a></li> <li><a href="https://forum.djangoproject.com/" target="_blank">Official Django Forum</a></li> </ul> </div> <div class="col-follow-us"> <h2>Follow Us</h2> <ul> <li><a href="https://github.com/django">GitHub</a></li> <li><a href="https://twitter.com/djangoproject">Twitter</a></li> <li><a href="https://fosstodon.org/@django" rel="me">Fediverse (Mastodon)</a></li> <li><a href="https://www.djangoproject.com/rss/weblog/">News RSS</a></li> <li><a href="https://groups.google.com/forum/#!forum/django-users">Django Users Mailing List</a></li> </ul> </div> <div class="col-support-us"> <h2>Support Us</h2> <ul> <li><a href="https://www.djangoproject.com/fundraising/">Sponsor Django</a></li> <li><a href="/foundation/corporate-membership/">Corporate membership</a></li> <li><a href="https://django.threadless.com/" target="_blank">Official merchandise store</a></li> <li><a href="/foundation/donate/#benevity-giving">Benevity Workplace Giving Program</a></li> </ul> </div> </div> </div> </div> <div class="footer"> <div class="container"> <div class="footer-logo"> <a class="logo" href="https://www.djangoproject.com/">Django</a> </div> <ul class="thanks"> <li> <span>Hosting by</span> <a class="in-kind-donors" href="https://www.djangoproject.com/fundraising/#in-kind-donors">In-kind donors</a> </li> <li class="design"><span>Design by</span> <a class="threespot" href="https://www.threespot.com">Threespot</a> <span class="ampersand">&amp;</span> <a class="andrevv" href="http://andrevv.com/">andrevv</a></li> </ul> <p class="copyright">&copy; 2005-2024 <a href="https://www.djangoproject.com/foundation/"> Django Software Foundation</a> and individual contributors. Django is a <a href="https://www.djangoproject.com/trademarks/">registered trademark</a> of the Django Software Foundation. </p> </div> </div> </div> <script> function extless(input) { return input.replace(/(.*)\.[^.]+$/, '$1'); } var require = { shim: { 'jquery': [], 'jquery.inview': ["jquery"], 'jquery.payment': ["jquery"], 'jquery.flot': ["jquery"], 'jquery.unveil': ["jquery"], 'stripe': { exports: 'Stripe' } }, paths: { "jquery": extless("https://static.djangoproject.com/js/lib/jquery/dist/jquery.min.eb6af28969bd.js"), "jquery.inview": extless("https://static.djangoproject.com/js/lib/jquery.inview/jquery.inview.min.4edba1c65592.js"), "jquery.payment": extless("https://static.djangoproject.com/js/lib/jquery.payment/lib/jquery.payment.e99c05ca79ae.js"), "jquery.unveil": extless("https://static.djangoproject.com/js/lib/unveil/jquery.unveil.min.ac79eb277093.js"), "jquery.flot": extless("https://static.djangoproject.com/js/lib/jquery-flot/jquery.flot.min.9964206e9d7f.js"), "clipboard": extless("https://static.djangoproject.com/js/lib/clipboard/dist/clipboard.min.bd70fd596a23.js"), "mod/floating-warning": extless("https://static.djangoproject.com/js/mod/floating-warning.a21b2abd2884.js"), "mod/list-collapsing": extless("https://static.djangoproject.com/js/mod/list-collapsing.c1a08d3ef9e9.js"), "mod/list-feature": extless("https://static.djangoproject.com/js/mod/list-feature.73529480f25b.js"), "mod/mobile-menu": extless("https://static.djangoproject.com/js/mod/mobile-menu.8e7e063d3524.js"), "mod/version-switcher": extless("https://static.djangoproject.com/js/mod/version-switcher.c56ff7ed5481.js"), "mod/search-key": extless("https://static.djangoproject.com/js/mod/search-key.ae7292327b47.js"), "mod/stripe-change-card": extless("https://static.djangoproject.com/js/mod/stripe-change-card.682c710317a8.js"), "mod/switch-dark-mode": extless("https://static.djangoproject.com/js/mod/switch-dark-mode.69777ee87b91.js"), "mod/console-tabs": extless("https://static.djangoproject.com/js/mod/console-tabs.70ce882faaf3.js"), "stripe-checkout": "https://checkout.stripe.com/checkout", "stripe": "https://js.stripe.com/v3/?" // ? needed due to require.js } }; </script> <script data-main="https://static.djangoproject.com/js/main.48270eac7c0b.js" src="https://static.djangoproject.com/js/lib/require.177879fbe7dd.js"></script> <div id="outdated-warning" class="doc-floating-warning"> This document is for an insecure version of Django that is no longer supported. Please upgrade to a newer release! </div> </body> </html>

Pages: 1 2 3 4 5 6 7 8 9 10