Brenden
Brenden

Reputation: 8774

301 redirect router for Django project

I have a website building tool created in Django and I'd like to add easy user defined 301 redirects to it.

Webflow has a very easy to understand tool for 301 redirects. You add a path (not just a slug) and then define where that path should lead the user.

enter image description here

I'd like to do the same for the Django project I'm working on. I currently allow users to set a slug that redirects /<slug:redirect_slug>/ and they can set to go to any URL. But I'd like them to be able to add, for example, the path for an old blog post '/2018/04/12/my-favorite-thing/'

What's the best URL conf to use in Django to safely accept any path the user wants?

Upvotes: 1

Views: 490

Answers (2)

Ronak Mutha
Ronak Mutha

Reputation: 314

Add a RerouteMiddleware which first checks if the request can be served by the existing URLs from the urls.py. If it cannot be served, check if the requested path is from the old -> new URLs mapping, if a match found redirect it to the new URL.

Sample piece of code to try it out.

    try:
        resolve(request.path_info)
    except Resolver404:
        # Check if the URL exists in your database/constants 
        # where you might have stored the old -> new URL mapping.
        if request.path is valid:
            new_url = # Retrieve the new URL
            return redirect(new_url)

    response = self.get_response(request)
    return response

Upvotes: 1

Bernardo Duarte
Bernardo Duarte

Reputation: 4264

You can use the Path Converters that convert the path parameters into appropriate types, which also includes a converter for urls.

An example would be like the following:

path('api/<path:encoded_url>/', YourView.as_view()),

As per the docs:

Matches any non-empty string, including the path separator, '/'. This allows you to match against a complete URL path rather than just a segment of a URL path as with str.

In your view, you can get your URL like this:

encoded_url = self.kwargs.get('encoded_url')

Upvotes: 1

Related Questions