In all Wagtail sites I setup, I enable the redirects app so that you can define redirects from the Admin pages. To set it up, you simply need to add it to the list of installed apps and to the middleware:
INSTALLED_APPS = [ ... 'wagtail.contrib.redirects', ... ] MIDDLEWARE = [ # ... # all other django middlware first 'wagtail.contrib.redirects.middleware.RedirectMiddleware', ]
To finish the installation, you also need to run the
migrate command to setup the database tables:
$ ./manage.py migrate
If you then go to the settings in the menu, you'll see that a new menu item appeared called "Redirects". In there, you can specify any redirect you want.
Now, if you are migrating from another site or web application, you'll probably have a whole bunch of redirects to create at once.At that point, it becomes useful to be able to add them in an automated way. You can do this by interacting with the
Redirect class directly:
from wagtail.core.models import Site from wagtail.core import hooks from wagtail.contrib.redirects.models import Redirect # Get a reference to the default site site = Site.objects.get(is_default_site=True) # Catch duplicate errors try: Redirect.objects.create( old_path="/old-path", redirect_link="/new-path", site=site, ) except IntegrityError as e: print('Redirect exists already')
Another use-case is to automatically create a redirect of the old slug to the new slug of a page when updating it. This can be done by using a Wagtail hook called
@hooks.register('before_edit_page') def create_redirect_on_slug_change(request, page): if request.method == 'POST': if page.slug != request.POST['slug']: Redirect.objects.create( old_path=page.url[:-1], site=page.get_site(), redirect_page=page )
There's one caveat with using the Wagtail redirects app and that is that it doesn't work for all URLs. It only works for requests that pass through Wagtail. If you want to use it to setup redirects for your media files, you'll need to look for another solution.
Media assets are most often served directly by the webserver and never reach the Wagtail code. The best solution to tackle this is to handle these on the webserver level.
There are many more use-cases, so feel free to experiment!