|
1 ================= |
|
2 The redirects app |
|
3 ================= |
|
4 |
|
5 Django comes with an optional redirects application. It lets you store simple |
|
6 redirects in a database and handles the redirecting for you. |
|
7 |
|
8 Installation |
|
9 ============ |
|
10 |
|
11 To install the redirects app, follow these steps: |
|
12 |
|
13 1. Add ``'django.contrib.redirects'`` to your INSTALLED_APPS_ setting. |
|
14 2. Add ``'django.contrib.redirects.middleware.RedirectFallbackMiddleware'`` |
|
15 to your MIDDLEWARE_CLASSES_ setting. |
|
16 3. Run the command ``manage.py syncdb``. |
|
17 |
|
18 .. _INSTALLED_APPS: ../settings/#installed-apps |
|
19 .. _MIDDLEWARE_CLASSES: ../settings/#middleware-classes |
|
20 |
|
21 How it works |
|
22 ============ |
|
23 |
|
24 ``manage.py syncdb`` creates a ``django_redirect`` table in your database. This |
|
25 is a simple lookup table with ``site_id``, ``old_path`` and ``new_path`` fields. |
|
26 |
|
27 The ``RedirectFallbackMiddleware`` does all of the work. Each time any Django |
|
28 application raises a 404 error, this middleware checks the redirects database |
|
29 for the requested URL as a last resort. Specifically, it checks for a redirect |
|
30 with the given ``old_path`` with a site ID that corresponds to the SITE_ID_ |
|
31 setting. |
|
32 |
|
33 * If it finds a match, and ``new_path`` is not empty, it redirects to |
|
34 ``new_path``. |
|
35 * If it finds a match, and ``new_path`` is empty, it sends a 410 ("Gone") |
|
36 HTTP header and empty (content-less) response. |
|
37 * If it doesn't find a match, the request continues to be processed as |
|
38 usual. |
|
39 |
|
40 The middleware only gets activated for 404s -- not for 500s or responses of any |
|
41 other status code. |
|
42 |
|
43 Note that the order of ``MIDDLEWARE_CLASSES`` matters. Generally, you can put |
|
44 ``RedirectFallbackMiddleware`` at the end of the list, because it's a last |
|
45 resort. |
|
46 |
|
47 For more on middleware, read the `middleware docs`_. |
|
48 |
|
49 .. _SITE_ID: ../settings/#site-id |
|
50 .. _middleware docs: ../middleware/ |
|
51 |
|
52 How to add, change and delete redirects |
|
53 ======================================= |
|
54 |
|
55 Via the admin interface |
|
56 ----------------------- |
|
57 |
|
58 If you've activated the automatic Django admin interface, you should see a |
|
59 "Redirects" section on the admin index page. Edit redirects as you edit any |
|
60 other object in the system. |
|
61 |
|
62 Via the Python API |
|
63 ------------------ |
|
64 |
|
65 Redirects are represented by a standard `Django model`_, which lives in |
|
66 `django/contrib/redirects/models.py`_. You can access redirect |
|
67 objects via the `Django database API`_. |
|
68 |
|
69 .. _Django model: ../model_api/ |
|
70 .. _django/contrib/redirects/models.py: http://code.djangoproject.com/browser/django/trunk/django/contrib/redirects/models.py |
|
71 .. _Django database API: ../db_api/ |