2013-02-19 10 views
76

他のURLと一致しないトラフィックをホームページにリダイレクトする方法を教えてください。 それは、最後のエントリは、ホームページにすべての「その他」のトラフィックを送信しますが、私はどちらかHTTP経由で301のまたは302Django URLリダイレクト

感謝をリダイレクトする現状では私の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'), 
) 

、のように見えます

答えて

131

あなたはクラスベースビューがでurlように注意してください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') 
) 

と呼ばれて試すことができます3210あなたは実際にURLを指定する必要があります。 permanent=Trueは、あなたが、別のroute-を私は同じようジャンゴ1.2上で立ち往生しているとRedirectViewが存在しない場合は別の方法としては、django.shortcuts.redirect

+1

+1は、URLのconfのクラスベースのビューです。 –

+0

私は常にクラスベースのビューを提唱することを忘れています+1 – danodonovan

+0

私はこれを追加しましたが、HTTP 500エラーがありますか? URL(r '^。* $'、RedirectView.as_view(url = 'macmon_about'、permanent = False) – felix001

8

を使用することができますHTTP 301

を返しますながら

permanent=Falseは、HTTP 302が返されます。リダイレクトマッピングを追加するための中心の方法が使用されます。

(r'^match_rules/$', 'django.views.generic.simple.redirect_to', {'url': '/new_url'}), 

あなたはまた、試合のすべてを再ルーティングすることができます。アプリのフォルダを変更することなく、ブックマークを保存したい場合に便利です:

(r'^match_folder/(?P<path>.*)', 'django.views.generic.simple.redirect_to', {'url': '/new_folder/%(path)s'}), 

これは、あなただけのURLルーティングを変更しようとしていると.htaccessへのアクセスを持っていない場合django.shortcuts.redirectすることが好ましいです。 、etc(私はAppengine上にあり、app.yamlは.htaccessのようなレベルでURLのリダイレクトを許可しません)。

+2

ありがとう、第二の変種は私を助けてくれました:) –

6

それを行うための別の方法は非常に似HttpResponsePermanentRedirectを使用している:view.py

Djangoの1.8では
def url_redirect(request): 
    return HttpResponsePermanentRedirect("/new_url/") 
url.pyで

url(r'^old_url/$', "website.views.url_redirect", name="url-redirect"), 
16

、これはどのようです私のことでした。

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を使用して、あなたは少し非DRYである、pattern_nameを使用することができ、そして、あなたのURLを変更することを確認します、あなたもリダイレクトを変更する必要はありません。

+1

私はこれが好きです!まだDjango 1.10で動作します:) – teewuane