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:
SecurityMiddlewareIt 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.
UpdateCacheMiddlewareBefore those that modify the
Varyheader (SessionMiddleware,GZipMiddleware,LocaleMiddleware).GZipMiddlewareBefore any middleware that may change or use the response body.
After
UpdateCacheMiddleware: ModifiesVaryheader.SessionMiddlewareAfter
UpdateCacheMiddleware: ModifiesVaryheader.ConditionalGetMiddlewareBefore any middleware that may change the response (it sets the
ETagheader).After
GZipMiddlewareso it won’t calculate anETagheader on gzipped contents.LocaleMiddlewareOne of the topmost, after
SessionMiddleware(uses session data) andUpdateCacheMiddleware(modifiesVaryheader).CommonMiddlewareBefore any middleware that may change the response (it sets the
Content-Lengthheader). A middleware that appears beforeCommonMiddlewareand changes the response must resetContent-Length.Close to the top: it redirects when APPEND_SLASH or PREPEND_WWW are set to
True.CsrfViewMiddlewareBefore any view middleware that assumes that CSRF attacks have been dealt with.
It must come after
SessionMiddlewareif you’re using CSRF_USE_SESSIONS.AuthenticationMiddlewareAfter
SessionMiddleware: uses session storage.MessageMiddlewareAfter
SessionMiddleware: can use session-based storage.FetchFromCacheMiddlewareAfter any middleware that modifies the
Varyheader: that header is used to pick a value for the cache hash-key.FlatpageFallbackMiddlewareShould be near the bottom as it’s a last-resort type of middleware.
RedirectFallbackMiddlewareShould be near the bottom as it’s a last-resort type of middleware.