通常、私はそれを行います.htaccess
が、djangoにはありません。
では、www.olddomain.com から www.newdomain.com にリダイレクトするための最良の方法とコードは何ですか?
注: Apache ではなく、Gunicorn を使用しています。
ありがとう!
これを行うための最良の方法は、DjangoではなくWebサーバーを使用することです。これは、Djangoで行うよりもはるかに高速で効率的です。
詳細については、この質問を確認してください。
アップデート
本当にdjango内でそれを実行したい場合は、url confファイル(djangoのurlディスパッチャーを管理する)を編集して、上部に次のものを含めます-
from django.views.generic.simple import redirect_to
urlpatterns = patterns('',
(r'^.*$', redirect_to, {'url': 'http://www.newdomain.com'}),
)
詳細については、ドキュメントを確認してください。
import urlparse
from django.http import HttpResponseRedirect
domain = request.GET['domain']
destination = reverse('variable_response',args=['Successful'])
full_address = urlparse.urljoin(domain, destination)
return HttpResponseRedirect(full_address)
私はherokuを使用してそれを行い、1つのWeb dyno(無料)をスピンアップしました。
#views.py
def redirect(request):
return render_to_response('redirect.html')
#redirect.html
<html>
<head>
<title>Blah</title>
<meta http-equiv="refresh" content="1;url=http://www.example.com">
</head>
<body>
<p>
Redirecting to our main site. If you're not redirected within a couple of seconds, click here:<br />
<a href="http://www.example.com">example.com</a>
</p>
</body>
</html>
そのような単純な。ここで同じ例を見つけることができます。
Python 3に更新されたキャサリンの回答に代わるものは次のとおりです。
from django.contrib.sites.shortcuts import get_current_site
from urllib.parse import urljoin
from django.http import HttpResponseRedirect
NEW_DOMAIN = 'www.newdomain.com'
それぞれに入れますview
:
def myView(request, my_id):
if request.META['HTTP_HOST'] != NEW_DOMAIN:
# remove the args if not needed
destination = reverse('url_tag', args=[my_id])
full_address = urljoin(DOMAIN, str(destination))
return HttpResponseRedirect(full_address)
# your view here
はurl_tag
で定義されたものurlpatterns
です。
私は簡単な解決策で終わりました:
return HttpResponse(f"<script>location.replace('https://example.com/');</script>")
ユーザーがウェブブラウザでスクリプトを無効にしない場合に機能します