pythondjangodjango-urls

How do I redirect by URL pattern in Django?


I have a Django based website. I would like to redirect URLs with the pattern servertest in them to the same URL except servertest should be replaced by server-test.

So for example the following URLs would be mapped be redirected as shown below:

http://acme.com/servertest/                        =>  http://acme.com/server-test/ 

http://acme.com/servertest/www.example.com         =>  http://acme.com/server-test/www.example.com

http://acme.com/servertest/www.example.com:8833    =>  http://acme.com/server-test/www.example.com:8833 

I can get the first example working using the following line in urls.py:

    ('^servertest/$', 'redirect_to', {'url': '/server-test/'}),

Not sure how to do it for the others so only the servetest part of the URL is replaced.


Solution

  • Use the following (updated for Django 2.2):

    re_path(r'^servertest/(?P<path>.*)$', 'redirect_to', {'url': '/server-test/%(path)s'}),
    

    It takes zero or more characters after servertest/ and places them after /server-test/.

    Alternatively, you can use new path function that covers simple cases url patterns without using regex (and it is preferred in new versions of Django):

    path('servertest/<path:path>', 'redirect_to', {'url': '/server-test/%(path)s'}),