6

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.

wowkin2
  • 5,895
  • 5
  • 23
  • 66
TonyM
  • 708
  • 1
  • 8
  • 15

3 Answers3

9

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'}),
GwynBleidD
  • 20,081
  • 5
  • 46
  • 77
Simeon Visser
  • 118,920
  • 18
  • 185
  • 180
  • aren't you missing `url()` - django says: `Ensure that urlpatterns is a list of url() instances. HINT: Try using url() instead of a tuple.` – User Sep 19 '19 at 02:52
7

It's covered in the docs.

The given URL may contain dictionary-style string formatting, which will be interpolated against the parameters captured in the URL. Because keyword interpolation is always done (even if no arguments are passed in), any "%" characters in the URL must be written as "%%" so that Python will convert them to a single percent sign on output.

(Strong emphasis mine.)

And then their examples:

This example issues a permanent redirect (HTTP status code 301) from /foo/<id>/ to /bar/<id>/:

from django.views.generic.simple import redirect_to

urlpatterns = patterns('',
    ('^foo/(?P<id>\d+)/$', redirect_to, {'url': '/bar/%(id)s/'}),
)

And so you see that it's just the nice straightforward form:

('^servertest/(?P<path>.*)$', 'redirect_to', {'url': '/server-test/%(path)s'}),
Chris Morgan
  • 86,207
  • 24
  • 208
  • 215
  • Before your edit I got this error: "redirect_to() got multiple values for keyword argument 'url'" so I tried the answer from Simeon Visser which worked. – TonyM Mar 29 '12 at 10:22
  • @TonyM: yeah, you can't use unnamed groups; they've got to be named. (I found that when I checked the source code, it's just `**kwargs`, not `*args`.) – Chris Morgan Mar 29 '12 at 12:58
0

Try this expression :

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

or this one:
('^servertest', 'redirect_to', {'url': '/server-test/'}),

andy
  • 89
  • 4