Django comes with an optional redirects application. It lets you store simple redirects in a database and handles the redirecting for you. It uses the HTTP response status code
301 Moved Permanently by default.
To install the redirects app, follow these steps:
django.contrib.sitesframework is installed.
manage.py migrate creates a
django_redirect table in your database. This is a simple lookup table with
RedirectFallbackMiddleware 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
new_pathis not empty, it redirects to
new_pathusing a 301 (“Moved Permanently”) redirect. You can subclass
django.http.HttpResponseRedirectto use a
302 Moved Temporarilyredirect instead.
new_pathis empty, it sends a 410 (“Gone”) HTTP header and empty (content-less) response.
The middleware only gets activated for 404s – not for 500s or responses of any other status code.
Note that the order of
MIDDLEWARE matters. Generally, you can put
RedirectFallbackMiddleware at the end of the list, because it’s a last resort.
For more on middleware, read the middleware docs.
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.
Redirects are represented by a standard Django model, which lives in django/contrib/redirects/models.py. You can access redirect objects via the Django database API.
You can change the
HttpResponse classes used by the middleware by creating a subclass of
RedirectFallbackMiddleware and overriding
HttpResponse class used when a
Redirect is not found for the requested path or has a blank
HttpResponse class that handles the redirect.
© Django Software Foundation and individual contributors
Licensed under the BSD License.