简体   繁体   English

Django别名将错误的URL重定向到正确的URL

[英]Django alias redirect on wrong url to the correct url

The question may have been asked many times, but I couldn't find something about this which is a basic stuff to do. 这个问题可能已经被问过很多次了,但是我找不到关于这的基本内容。 I have a problem with my website one of the sub urls of google search redirects to the wrong page. 我的网站出现问题,将Google搜索的子网址之一重定向到错误的页面。

Here are the urls : 这是网址:

www.example.com/login/user/ #wrong url

www.example.com/accounts/login/ #correct url

urls.py : url(r'^accounts/login/$', auth_views.login, name='login'),

I'd like the user to be redirected to the correct url if he access the wrong one. 如果用户访问错误的网址,我希望将其重定向到正确的网址。 I know that it is possible to do that with views using redirect(reverse('...')) but doing it just for this purpose doesn't sound like the best way. 我知道可以使用redirect(reverse('...'))使用视图来做到这一点,但是这样做似乎并不是最好的方法。

Is there a way to redirect an user when he enters a wrong url to another one only by using urls.py ? 当用户仅使用urls.py输入错误的URL时,是否可以将用户重定向到另一个URL?

You would normally do this on your webserver, eg Apache 通常,您可以在网络服务器上执行此操作,例如Apache

RewriteRule /login/user/ /accounts/login/ [R=301,L]

That way you don't need to load Django to do a static redirect (you might build up a longer list of these as site-designs evolve). 这样,您无需加载Django即可进行静态重定向(随着站点设计的发展,您可能会建立更长的列表)。

One solution is to use the RedirectView inside urls.py as shown here in the docs 一种解决方案是使用urls.pyRedirectView ,如文档所示

So, for example: 因此,例如:

url(r'^login/user$', RedirectView.as_view(pattern_name='login')),

To urls.py , you can add: 要添加到urls.py ,您可以添加:

url(r'^login/user/$', auth_views.login, name='login')

It seems like you are aware of that. 您似乎已经意识到这一点。 Did I not understand your question? 我不明白你的问题吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM