Latest Version: 0.9.6.2
  Dashboard > Pylons Cookbook > ... > Controllers > Adding trailing slash to pages automatically
  Pylons Cookbook Log In | Sign Up   View a printable version of the current page.  
  Adding trailing slash to pages automatically
Added by Max Ischenko, last edited by Art on Dec 06, 2007  (view change) show comment
Labels: 

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.

Site running on a free Atlassian Confluence Open Source Project License granted to Pylons. Evaluate Confluence today.
Powered by Atlassian Confluence, the Enterprise Wiki. (Version: 2.3.3 Build:#645 Feb 13, 2007) - Bug/feature request - Contact Administrators
Top