Django URL 重定向

131 投票
5 回答
147444 浏览
提问于 2025-04-17 16:22

我该怎么做才能把那些不符合我其他网址的流量重定向回主页呢?

urls.py:

urlpatterns = patterns('',
    url(r'^$', 'macmonster.views.home'),
    #url(r'^macmon_home$', 'macmonster.views.home'),
    url(r'^macmon_output/$', 'macmonster.views.output'),
    url(r'^macmon_about/$', 'macmonster.views.about'),
    url(r'^.*$',  'macmonster.views.home'),
)

现在最后一条记录会把所有“其他”的流量发送到主页,但我想通过HTTP 301302来进行重定向。

5 个回答

23

其他的方法都很好用,但你也可以使用老牌的 django.shortcut.redirect

下面的代码是摘自 这个回答

在 Django 2.x 中:

from django.shortcuts import redirect
from django.urls import path, include

urlpatterns = [
    # this example uses named URL 'hola-home' from app named hola
    # for more redirect's usage options: https://docs.djangoproject.com/en/2.1/topics/http/shortcuts/
    path('', lambda request: redirect('hola/', permanent=True)),
    path('hola/', include('hola.urls')),
]
40

在Django 1.8中,我是这样做的。

from django.views.generic.base import RedirectView

url(r'^$', views.comingSoon, name='homepage'),
# whatever urls you might have in here
# make sure the 'catch-all' url is placed last
url(r'^.*$', RedirectView.as_view(pattern_name='homepage', permanent=False))

与其使用url,你可以用pattern_name,虽然这样有点不够简洁,但这样一来,如果你更改了网址,就不需要再去改重定向的部分了。

225

你可以试试一种叫做 RedirectView 的类视图。

from django.views.generic.base import RedirectView

urlpatterns = patterns('',
    url(r'^$', 'macmonster.views.home'),
    #url(r'^macmon_home$', 'macmonster.views.home'),
    url(r'^macmon_output/$', 'macmonster.views.output'),
    url(r'^macmon_about/$', 'macmonster.views.about'),
    url(r'^.*$', RedirectView.as_view(url='<url_to_home_view>', permanent=False), name='index')
)

注意,在 <url_to_home_view> 中,url 需要你实际指定一个网址。

permanent=False 会返回 HTTP 302,而 permanent=True 会返回 HTTP 301。

另外,你也可以使用 django.shortcuts.redirect

关于 Django 2+ 版本的更新

在 Django 2+ 中,url() 已经被淘汰,取而代之的是 re_path()。用法和 url() 一样,都是使用正则表达式。如果不需要正则表达式,可以使用 path()

from django.urls import re_path

re_path(r'^.*$', RedirectView.as_view(url='<url_to_home_view>', permanent=False), name='index')

撰写回答