Brenden
Brenden

Reputation: 8754

Make Django URLs work with or without /

I have a django app that has / at the end of every URL conf. Example:

# user home page
(r'^home/$', 'user_home_page'),

However, I'm noticing this is causing a ton of redirects on my server, because when people dont add the /, it redirects them. Is there any way to have it accept both without a redirect except doing:

# user home page
(r'^home$', 'user_home_page'),
(r'^home/$', 'user_home_page'),

or should I avoid URL confs like that?

Upvotes: 5

Views: 1850

Answers (6)

Sepero
Sepero

Reputation: 4677

Use Django REMOVE_SLASH middleware instead.

https://gist.github.com/2204099

https://gist.github.com/gists/2204099/download

Upvotes: 1

AndyBeard
AndyBeard

Reputation: 71

You need to ensure your application uses / consistently, make a choice which to use, and 301 redirect the rogue variation to the correct canonical one.

There should only be one version of a page, and the correct solution is in most cases to 301 redirect to the canonical version.

In some situations with additional paramenters for tracking you should also define a canonical in the head.

By using consistent URLs within your APP and out on the web in links pointing back to your app, you then won't have lots of redirects.

Upvotes: 0

Rusty Rob
Rusty Rob

Reputation: 17173

You could modify your APPEND_SLASH Django setting, I haven't used it before.

You may be wondering what happens if someone requests the URL /hello (that is, without a trailing slash). Because our URLpattern requires a trailing slash, that URL would not match. However, by default, any request to a URL that doesn’t match a URLpattern and doesn’t end with a slash will be redirected to the same URL with a trailing slash. (This is regulated by the APPEND_SLASH Django setting, which is covered in Appendix D.)

This was taken from http://djangobook.com/en/2.0/chapter03/

Upvotes: 6

S.Lott
S.Lott

Reputation: 391820

should I avoid URL confs like that?

Yes. Django already handles this for you.

See this: https://docs.djangoproject.com/en/1.3/ref/middleware/#module-django.middleware.common

If APPEND_SLASH is True and the initial URL doesn’t end with a slash, and it is not found in the URLconf, then a new URL is formed by appending a slash at the end. If this new URL is found in the URLconf, then Django redirects the request to this new URL. Otherwise, the initial URL is processed as usual.

Upvotes: 2

user9876
user9876

Reputation: 11102

The patterns are Python regular expressions. How about:

(r'^home(/?)$', 'user_home_page'),

Upvotes: 2

zackdever
zackdever

Reputation: 1642

While you can accept both without doing a redirect by using:

(r'^home/?$', 'user_home_page'),

It is not best SEO practice because it will look like you have duplicate content and your hits will be split between the two pages.

Upvotes: 8

Related Questions