如何在Django中通过URL模式重定向?


问题内容

我有一个基于Django的网站。我想将其中包含模式的URL重定向servertest到相同的URL,但servertest应替换为server- test

因此,例如,以下URL将被映射,如下所示:

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

我可以使用urls.py中的以下行来获取第一个示例:

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

不确定如何为其他用户执行此操作,因此仅替换了URL的servetest部分。


问题答案:

使用以下内容(针对Django 2.2更新):

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

其后需要零个或多个字符,servertest/然后将其放置在后面/server-test/

或者,您可以使用新path功能来覆盖简单情况下的网址格式,而无需使用正则表达式(在新版本的Django中首选):

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