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
- Template tag - list punctuation for a list of items by shapiromatron 10 months ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 1 week ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 5 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
isn't that obsolet?
https://docs.djangoproject.com/en/dev/ref/settings/#append-slash
#
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.
#
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.