PylonsHQ.

Layout: Fixed-width

Adding trailing slash to pages automatically

From a search engine point of view, it is important that every url in your application has one canonical location. It's not true by default in your Pylons app but it is easy to fix.

Step 1: Fix url generation.

Routes has undocumented append_slash option which adds trailing '/' to every url it is asked to generate for you. So update your routing.py like this:

1
2
map = Mapper(...)
map.append_slash = True

Step 2: Add redirects to canonical location.

In addition to correct urls you also want to redirect user to canonical page location if the '/' wasn't specified. One possible solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# this is appproj/lib/base.py

from paste.request import construct_url
from paste.httpexceptions import HTTPMovedPermanently

class BaseController(WSGIController):
    # ...
    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        if not environ['PATH_INFO'].endswith('/'):
            environ['PATH_INFO'] += '/'
            url = construct_url(environ)
            raise HTTPMovedPermanently(url)
        return WSGIController.__call__(self, environ, start_response)

Step 3: Set up the middleware.

Adjust appproj/config/middleware.py

In the imports:

1
from paste import httpexceptions

In make_app after instantiating the PylonsApp

1
app = httpexceptions.make_middleware(app, global_conf)

References.

Labels

recipes recipes Delete
routes routes Delete
controllers controllers Delete
Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.

Powered by Pylons - Contact Administrators