The redirects app
To install the redirects app, follow these steps:
- Ensure that the
django.contrib.sites
framework . - Add
'django.contrib.redirects'
to yourINSTALLED_APPS
setting. - Add
'django.contrib.redirects.middleware.RedirectFallbackMiddleware'
to your setting.
manage.py migrate
creates a django_redirect
table in your database. This is a lookup table with site_id
, old_path
and new_path
fields.
The does all of the work. Each time any Django application raises a 404 error, this middleware checks the redirects database for the requested URL as a last resort. Specifically, it checks for a redirect with the given old_path
with a site ID that corresponds to the setting.
- If it finds a match, and
new_path
is not empty, it redirects tonew_path
using a 301 (“Moved Permanently”) redirect. You can subclassRedirectFallbackMiddleware
and set todjango.http.HttpResponseRedirect
to use a302 Moved Temporarily
redirect instead. - If it finds a match, and
new_path
is empty, it sends a 410 (“Gone”) HTTP header and empty (content-less) response. - If it doesn’t find a match, the request continues to be processed as usual.
The middleware only gets activated for 404s — not for 500s or responses of any other status code.
Note that the order of matters. Generally, you can put RedirectFallbackMiddleware
at the end of the list, because it’s a last resort.
If you’ve activated the automatic Django admin interface, you should see a “Redirects” section on the admin index page. Edit redirects as you edit any other object in the system.
Via the Python API
class
Redirects are represented by a standard Django model, which lives in . You can access redirect objects via the Django database API. For example:
class middleware.``RedirectFallbackMiddleware
You can change the HttpResponse
classes used by the middleware by creating a subclass of and overriding response_gone_class
and/or response_redirect_class
.
-
The
HttpResponse
class used when a is not found for the requested path or has a blanknew_path
value.Defaults to
HttpResponseGone
.