Horai Nuri
Horai Nuri

Reputation: 5578

how to manage Django urls alias redirections?

I'd like set up my urls correctly avoiding doing it like the example below since it afects my Google indexation :

urls.py (wrong way) :

url(r'^virtual-reality/$', views.virtualreality, name="virtual-reality"),
url(r'^virtual-reality$', views.virtualreality, name="virtual-reality"),
url(r'^vr/$', views.virtualreality, name="virtual-reality"),
url(r'^vr$', views.virtualreality, name="virtual-reality"),

As you can see I'd like vr/, vr, virtual-reality/, virtual-reality to redirect to the same page. I have more than 30 urls on my site and doing each url redirection like this is problematic since the structure grows.

I do not use Apache on my Django site, so Rewriting Rules can not be made. (I'm on pythonanywhere (webserver : Gunicorn))

What's the best way to redirect all types of aliases in the same view without affecting my google search indexation and avoid to enter each url with the same view to urls.py ?

Upvotes: 2

Views: 3198

Answers (3)

Lutz Prechelt
Lutz Prechelt

Reputation: 39426

urls.py is Python after all

Just write a suitable data structure that can capture what you want and use a loop to generate the list containing the url() calls from that.

Upvotes: 1

julio
julio

Reputation: 46

Another way to solve the trailing slash problem, is to use ? flag in the regex.

url(r'^virtual-reality/?$', views.virtualreality, name="virtual-reality"),
url(r'^vr/?$', views.virtualreality, name="virtual-reality"),

If using CommonMiddleware, it adds the trailing slash and return the view with it (if the version without the trailing slash is not found in any urlpattern). It can be seen in the documentation.

Upvotes: 2

Gabriel Muj
Gabriel Muj

Reputation: 3815

Best way to do it is using django redirect app https://docs.djangoproject.com/en/1.10/ref/contrib/redirects/ you can easily manage redirects from the admin with this.

Upvotes: 3

Related Questions