如何在django应用中从一个域名重定向到另一个域名?

wj8zmpe1  于 2023-02-17  发布在  Go
关注(0)|答案(8)|浏览(194)

通常我会用.htaccess来做,但是django没有。
那么,从www.example.com重定向到www.example.com的最佳方法是什么?代码是www.olddomain.comwww.newdomain.com?
注意:我们使用的不是Apache,而是Gunicorn
谢谢!

lf3rwulv

lf3rwulv1#

最好的方法仍然是使用你的Web服务器而不是Django,这样做会比使用Django更快更有效。
查看this question了解更多信息。
更新
如果你真的想在django中完成它,那么编辑你的url conf文件(它管理django's url dispatcher),在顶部包含以下内容-

from django.views.generic.simple import redirect_to

urlpatterns = patterns('',   
    (r'^.*$', redirect_to, {'url': 'http://www.newdomain.com'}),
)

有关详细信息,请查看文档。

6rvt4ljy

6rvt4ljy2#

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)
z2acfund

z2acfund3#

我也有同样的问题,所以我写了这个,它对我来说非常有效,也许别人也需要它:

urlpatterns += [  # redirect to media server with same path
url(r'^media/', redirectMedia),
]

并使用此函数重定向:

from urllib.request import urlopen
from django.http import HttpResponse
def redirectMedia(request):
    x = urlopen("http://www.newdomain.com" + request.path)
    return HttpResponse(x.read())

好好享受吧!

egdjgwm8

egdjgwm84#

对于Django〉= 2.0,更简单的解决方案是使用RedirectView
例如,在urls.py中:

from django.views.generic.base import RedirectView

urlpatterns = [
    path('my_ext_uri', RedirectView.as_view(url='https://YOUR_EXTERNAL_URL')),
]

[Side注]
正如Aidan的回答中所提到的,最好重定向将由Web服务器网关上的不同服务处理的请求,而不是在(Python/Django)应用服务器上。

pxy2qtax

pxy2qtax5#

我最终使用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>

就这么简单。可以找到相同的示例here

3qpi33ja

3qpi33ja6#

catherine答案的另一种选择(更新到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中定义的。

camsedfj

camsedfj7#

最后我给出了一个简单的解决方案:

return HttpResponse(f"<script>location.replace('https://example.com/');</script>")

如果用户不禁用网页浏览器中的脚本,它就可以工作

snvhrwxg

snvhrwxg8#

你可以简单地在'urls.py'中找到的'urlpattens'值中添加重定向。希望它能有所帮助。参考是source

from django.shortcuts import redirect

urlpatterns = [
    path('old-path/', lambda request: redirect('new-path/', permanent=False)),
]

相关问题