middleware.txt 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. ==========
  2. Middleware
  3. ==========
  4. .. module:: django.middleware
  5. :synopsis: Django's built-in middleware classes.
  6. This document explains all middleware components that come with Django. For
  7. information on how to use them and how to write your own middleware, see
  8. the :doc:`middleware usage guide </topics/http/middleware>`.
  9. Available middleware
  10. ====================
  11. Cache middleware
  12. ----------------
  13. .. module:: django.middleware.cache
  14. :synopsis: Middleware for the site-wide cache.
  15. .. class:: UpdateCacheMiddleware
  16. .. class:: FetchFromCacheMiddleware
  17. Enable the site-wide cache. If these are enabled, each Django-powered page will
  18. be cached for as long as the :setting:`CACHE_MIDDLEWARE_SECONDS` setting
  19. defines. See the :doc:`cache documentation </topics/cache>`.
  20. "Common" middleware
  21. -------------------
  22. .. module:: django.middleware.common
  23. :synopsis: Middleware adding "common" conveniences for perfectionists.
  24. .. class:: CommonMiddleware
  25. Adds a few conveniences for perfectionists:
  26. * Forbids access to user agents in the :setting:`DISALLOWED_USER_AGENTS`
  27. setting, which should be a list of compiled regular expression objects.
  28. * Performs URL rewriting based on the :setting:`APPEND_SLASH` and
  29. :setting:`PREPEND_WWW` settings.
  30. If :setting:`APPEND_SLASH` is ``True`` and the initial URL doesn't end
  31. with a slash, and it is not found in the URLconf, then a new URL is
  32. formed by appending a slash at the end. If this new URL is found in the
  33. URLconf, then Django redirects the request to this new URL. Otherwise,
  34. the initial URL is processed as usual.
  35. For example, ``foo.com/bar`` will be redirected to ``foo.com/bar/`` if
  36. you don't have a valid URL pattern for ``foo.com/bar`` but *do* have a
  37. valid pattern for ``foo.com/bar/``.
  38. If :setting:`PREPEND_WWW` is ``True``, URLs that lack a leading "www."
  39. will be redirected to the same URL with a leading "www."
  40. Both of these options are meant to normalize URLs. The philosophy is that
  41. each URL should exist in one, and only one, place. Technically a URL
  42. ``foo.com/bar`` is distinct from ``foo.com/bar/`` -- a search-engine
  43. indexer would treat them as separate URLs -- so it's best practice to
  44. normalize URLs.
  45. * Handles ETags based on the :setting:`USE_ETAGS` setting. If
  46. :setting:`USE_ETAGS` is set to ``True``, Django will calculate an ETag
  47. for each request by MD5-hashing the page content, and it'll take care of
  48. sending ``Not Modified`` responses, if appropriate.
  49. .. class:: BrokenLinkEmailsMiddleware
  50. * Sends broken link notification emails to :setting:`MANAGERS` (see
  51. :doc:`/howto/error-reporting`).
  52. GZip middleware
  53. ---------------
  54. .. module:: django.middleware.gzip
  55. :synopsis: Middleware to serve GZipped content for performance.
  56. .. class:: GZipMiddleware
  57. .. warning::
  58. Security researchers recently revealed that when compression techniques
  59. (including ``GZipMiddleware``) are used on a website, the site becomes
  60. exposed to a number of possible attacks. These approaches can be used to
  61. compromise, among other things, Django's CSRF protection. Before using
  62. ``GZipMiddleware`` on your site, you should consider very carefully whether
  63. you are subject to these attacks. If you're in *any* doubt about whether
  64. you're affected, you should avoid using ``GZipMiddleware``. For more
  65. details, see the `the BREACH paper (PDF)`_ and `breachattack.com`_.
  66. .. _the BREACH paper (PDF): http://breachattack.com/resources/BREACH%20-%20SSL,%20gone%20in%2030%20seconds.pdf
  67. .. _breachattack.com: http://breachattack.com
  68. Compresses content for browsers that understand GZip compression (all modern
  69. browsers).
  70. This middleware should be placed before any other middleware that need to
  71. read or write the response body so that compression happens afterward.
  72. It will NOT compress content if any of the following are true:
  73. * The content body is less than 200 bytes long.
  74. * The response has already set the ``Content-Encoding`` header.
  75. * The request (the browser) hasn't sent an ``Accept-Encoding`` header
  76. containing ``gzip``.
  77. * The request is from Internet Explorer and the ``Content-Type`` header
  78. contains ``javascript`` or starts with anything other than ``text/``.
  79. We do this to avoid a bug in early versions of IE that caused decompression
  80. not to be performed on certain content types.
  81. You can apply GZip compression to individual views using the
  82. :func:`~django.views.decorators.gzip.gzip_page()` decorator.
  83. Conditional GET middleware
  84. --------------------------
  85. .. module:: django.middleware.http
  86. :synopsis: Middleware handling advanced HTTP features.
  87. .. class:: ConditionalGetMiddleware
  88. Handles conditional GET operations. If the response has a ``ETag`` or
  89. ``Last-Modified`` header, and the request has ``If-None-Match`` or
  90. ``If-Modified-Since``, the response is replaced by an
  91. :class:`~django.http.HttpResponseNotModified`.
  92. Also sets the ``Date`` and ``Content-Length`` response-headers.
  93. Reverse proxy middleware
  94. ------------------------
  95. .. class:: SetRemoteAddrFromForwardedFor
  96. This middleware was removed in Django 1.1. See :ref:`the release notes
  97. <removed-setremoteaddrfromforwardedfor-middleware>` for details.
  98. Locale middleware
  99. -----------------
  100. .. module:: django.middleware.locale
  101. :synopsis: Middleware to enable language selection based on the request.
  102. .. class:: LocaleMiddleware
  103. Enables language selection based on data from the request. It customizes
  104. content for each user. See the :doc:`internationalization documentation
  105. </topics/i18n/translation>`.
  106. .. attribute:: LocaleMiddleware.response_redirect_class
  107. Defaults to :class:`~django.http.HttpResponseRedirect`. Subclass
  108. ``LocaleMiddleware`` and override the attribute to customize the redirects
  109. issued by the middleware.
  110. Message middleware
  111. ------------------
  112. .. module:: django.contrib.messages.middleware
  113. :synopsis: Message middleware.
  114. .. class:: MessageMiddleware
  115. Enables cookie- and session-based message support. See the
  116. :doc:`messages documentation </ref/contrib/messages>`.
  117. Session middleware
  118. ------------------
  119. .. module:: django.contrib.sessions.middleware
  120. :synopsis: Session middleware.
  121. .. class:: SessionMiddleware
  122. Enables session support. See the :doc:`session documentation
  123. </topics/http/sessions>`.
  124. Site middleware
  125. ---------------
  126. .. module:: django.contrib.sites.middleware
  127. :synopsis: Site middleware.
  128. .. class:: CurrentSiteMiddleware
  129. .. versionadded:: 1.7
  130. Adds the ``site`` attribute representing the current site to every incoming
  131. ``HttpRequest`` object. See the :ref:`sites documentation <site-middleware>`.
  132. Authentication middleware
  133. -------------------------
  134. .. module:: django.contrib.auth.middleware
  135. :synopsis: Authentication middleware.
  136. .. class:: AuthenticationMiddleware
  137. Adds the ``user`` attribute, representing the currently-logged-in user, to
  138. every incoming ``HttpRequest`` object. See :ref:`Authentication in Web requests
  139. <auth-web-requests>`.
  140. .. class:: RemoteUserMiddleware
  141. Middleware for utilizing Web server provided authentication. See
  142. :doc:`/howto/auth-remote-user` for usage details.
  143. .. class:: SessionAuthenticationMiddleware
  144. .. versionadded:: 1.7
  145. Allows a user's sessions to be invalidated when their password changes. See
  146. :ref:`session-invalidation-on-password-change` for details. This middleware must
  147. appear after :class:`django.contrib.auth.middleware.AuthenticationMiddleware`
  148. in :setting:`MIDDLEWARE_CLASSES`.
  149. CSRF protection middleware
  150. --------------------------
  151. .. module:: django.middleware.csrf
  152. :synopsis: Middleware adding protection against Cross Site Request
  153. Forgeries.
  154. .. class:: CsrfViewMiddleware
  155. Adds protection against Cross Site Request Forgeries by adding hidden form
  156. fields to POST forms and checking requests for the correct value. See the
  157. :doc:`Cross Site Request Forgery protection documentation </ref/contrib/csrf>`.
  158. X-Frame-Options middleware
  159. --------------------------
  160. .. module:: django.middleware.clickjacking
  161. :synopsis: Clickjacking protection
  162. .. class:: XFrameOptionsMiddleware
  163. Simple :doc:`clickjacking protection via the X-Frame-Options header </ref/clickjacking/>`.
  164. .. _middleware-ordering:
  165. Middleware ordering
  166. ===================
  167. Here are some hints about the ordering of various Django middleware classes:
  168. #. :class:`~django.middleware.cache.UpdateCacheMiddleware`
  169. Before those that modify the ``Vary`` header (``SessionMiddleware``,
  170. ``GZipMiddleware``, ``LocaleMiddleware``).
  171. #. :class:`~django.middleware.gzip.GZipMiddleware`
  172. Before any middleware that may change or use the response body.
  173. After ``UpdateCacheMiddleware``: Modifies ``Vary`` header.
  174. #. :class:`~django.middleware.http.ConditionalGetMiddleware`
  175. Before ``CommonMiddleware``: uses its ``Etag`` header when
  176. :setting:`USE_ETAGS` = ``True``.
  177. #. :class:`~django.contrib.sessions.middleware.SessionMiddleware`
  178. After ``UpdateCacheMiddleware``: Modifies ``Vary`` header.
  179. #. :class:`~django.middleware.locale.LocaleMiddleware`
  180. One of the topmost, after ``SessionMiddleware`` (uses session data) and
  181. ``CacheMiddleware`` (modifies ``Vary`` header).
  182. #. :class:`~django.middleware.common.CommonMiddleware`
  183. Before any middleware that may change the response (it calculates ``ETags``).
  184. After ``GZipMiddleware`` so it won't calculate an ``ETag`` header on gzipped
  185. contents.
  186. Close to the top: it redirects when :setting:`APPEND_SLASH` or
  187. :setting:`PREPEND_WWW` are set to ``True``.
  188. #. :class:`~django.middleware.csrf.CsrfViewMiddleware`
  189. Before any view middleware that assumes that CSRF attacks have been dealt
  190. with.
  191. #. :class:`~django.contrib.auth.middleware.AuthenticationMiddleware`
  192. After ``SessionMiddleware``: uses session storage.
  193. #. :class:`~django.contrib.messages.middleware.MessageMiddleware`
  194. After ``SessionMiddleware``: can use session-based storage.
  195. #. :class:`~django.middleware.cache.FetchFromCacheMiddleware`
  196. After any middleware that modifies the ``Vary`` header: that header is used
  197. to pick a value for the cache hash-key.
  198. #. :class:`~django.contrib.flatpages.middleware.FlatpageFallbackMiddleware`
  199. Should be near the bottom as it's a last-resort type of middleware.
  200. #. :class:`~django.contrib.redirects.middleware.RedirectFallbackMiddleware`
  201. Should be near the bottom as it's a last-resort type of middleware.