Sunday, February 13, 2011

Trailing slashes in Pylons Routes

What is the best way to make trailing slashes not matter in the latest version of Routes (1.10)? I currently am using the clearly non-DRY:

map.connect('/logs/', controller='logs', action='logs')
map.connect('/logs', controller='logs', action='logs')

I think that turning minimization on would do the trick, but am under the impression that it was disabled in the newer versions of Routes for a reason. Unfortunately documentation doesn't seem to have caught up with Routes development, so I can't find any good resources to go to. Any ideas?

  • There are two possible ways to solve this:

    1. Do it entirely in pylons.
    2. Add an htaccess rule to rewrite the trailing slash.

    Personally I don't like the trailing slash, because if you have a uri like:

    http://example.com/people

    You should be able to get the same data in xml format by going to:

    http://example.com/people.xml

    Marius Gedminas : Easily guessable URLs are good, so people ought to be allowed to go to /people and /people/ and see the same thing. Canonical URLs are also good, so one of those should redirect to the other.
    From jonnii
  • http://www.siafoo.net/snippet/275 has a basic piece of middleware which removes a trailing slash from requests. Clever idea, and I understood the concept of middleware in WSGI applications much better after I realised what this does.

    From AML
  • The following snippet added as the very last route worked for me:

    map.redirect('/*(url)/', '/{url}',
                 _redirect_code='301 Moved Permanently')
    
    Marius Gedminas : I'm 90% sure I found it somewhere on the net, but I cannot provide a proper attribution at the moment.
    Nick Retallack : This works and is a lot simpler than all the other solutions. You deserve upvotes, good sir.
    John : This worked great! Thanks!

0 comments:

Post a Comment