Login

Redirect to no slash

Author:
grillermo
Posted:
January 21, 2012
Language:
Python
Version:
1.3
Score:
0 (after 0 ratings)

The canonical notion of urls ending in slashes dates from a web where urls were used to access documents and files this is no longer the case so keeping your urls witouth trailing slashes makes them prettier. The problem is that many people/blogs/spiders/browsers could end up with a url with slashes which can be problematic for you SEO, or confuse users.

This script is for sites with no trailing slash dicipline in their urls, and to prevent everybody getting a horrible 404 for a simple slash you just got to remove it and issue a permanent redirect (301) and you'll get your pretty urls your cake and eat it too.

I must stress, you will have to edit all your public urls removing the slashes like so:

url(r'^login$', login,} If you forget, to edit them and visit the url, your browser will remember the redirect and you'll have to clean the browsing history to fix it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#mymiddleware.py
class RedirectToNoSlash(object):
    def process_request(self,request):
        if '/admin' not in request.path and request.path != '/':
            if request.path[-1] == '/':
                return HttpResponsePermanentRedirect(request.path[:-1]) 

#settings.py
MIDDLEWARE_CLASSES = (
    'mymiddleware.RedirectToNoSlash',
    ...            
)

#Make sure its the first middleware, or its before any url manipulating middleware such as CommonMiddleware.

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 3 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

klemens (on January 23, 2012):

isn't that obsolet?

https://docs.djangoproject.com/en/dev/ref/settings/#append-slash

#

coredumperror (on May 26, 2016):

No, it's not obsolete. It fills the niche of people who want the benefits of having one version of the URL redirect to the other version (the effect of django's CommonMiddleware, which is good for SEO), but they want to keep the slashless version of the URL, rather than the slashed one.

#

scythargon (on September 20, 2021):

There is a problem with this snippet - when opening a malicious url like yourdomain.com//google.com/ - request.path becomes //google.com and you are getting redirected to Google.

#

Please login first before commenting.