Middleware¶
Middleware ordering¶
Re: whitenoise middleware: The WhiteNoise middleware should be placed directly after the Django SecurityMiddleware (if you are using it) and before all other middleware:
Mostly copy of the Django middleware docs (2.1):
Here are some hints about the ordering of various Django middleware classes:
SecurityMiddleware
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.
UpdateCacheMiddleware
Before those that modify the
Vary
header (SessionMiddleware
,GZipMiddleware
,LocaleMiddleware
).GZipMiddleware
Before any middleware that may change or use the response body.
After
UpdateCacheMiddleware
: ModifiesVary
header.SessionMiddleware
After
UpdateCacheMiddleware
: ModifiesVary
header.ConditionalGetMiddleware
Before any middleware that may change the response (it sets the
ETag
header).After
GZipMiddleware
so it won’t calculate anETag
header on gzipped contents.LocaleMiddleware
One of the topmost, after
SessionMiddleware
(uses session data) andUpdateCacheMiddleware
(modifiesVary
header).CommonMiddleware
Before any middleware that may change the response (it sets the
Content-Length
header). A middleware that appears beforeCommonMiddleware
and changes the response must resetContent-Length
.Close to the top: it redirects when APPEND_SLASH or PREPEND_WWW are set to
True
.CsrfViewMiddleware
Before any view middleware that assumes that CSRF attacks have been dealt with.
It must come after
SessionMiddleware
if you’re using CSRF_USE_SESSIONS.AuthenticationMiddleware
After
SessionMiddleware
: uses session storage.MessageMiddleware
After
SessionMiddleware
: can use session-based storage.FetchFromCacheMiddleware
After any middleware that modifies the
Vary
header: that header is used to pick a value for the cache hash-key.FlatpageFallbackMiddleware
Should be near the bottom as it’s a last-resort type of middleware.
RedirectFallbackMiddleware
Should be near the bottom as it’s a last-resort type of middleware.