Intridea Company Blog
Utilize Canonical URLs in Your Rails Applications
Today came the announcement that all of the major search engines are going to support a ‘canonical’ URL hint that will allow site owners to specify a single URL for content that may be replicated across many URLs (such as for categories etc.).
To make use of this in Rails applications, I’ve written a plugin that allows you to easily specify canonical URLs for your content. To install it as a gem, just add this to your environment.rb:
config.gem 'mbleigh-canonical-url', :source => 'http://gems.github.com', :lib => 'canonical_url'
Using it is extremely simple; just add this to the <head> section of your layout:
<%= canonical_link_tag %>
And in your controllers, any time you want to specify a canonical URL you can do so like this:
class BlogController < ApplicationController
def show
@post = find_post # assume this is a standard blog post type record
canonical_url blog_post_path(post.year, post.month, post.day, post.slug)
end
end
Now any time the show action is run, no matter how the routing came to be there, a single canonical URL will be shown in the header. If no canonical URL is specified in the controller (or through the canonical_link_tag helper directly) the helper will not output anything, making it completely harmless to add to any application.
The source for the plugin is available on GitHub. So go forth and canonize your applications!
The Intridea Blogs
Blog Archive
- January 2010 (5)
- November 2009 (4)
- October 2009 (4)
- September 2009 (2)
- August 2009 (5)
- July 2009 (3)
- June 2009 (7)
- May 2009 (4)
- April 2009 (6)
- March 2009 (15)
- February 2009 (18)
- January 2009 (4)
- December 2008 (2)
- November 2008 (3)
- October 2008 (7)
- September 2008 (9)
- August 2008 (2)
- July 2008 (7)
- June 2008 (14)
- May 2008 (5)
- April 2008 (14)
- March 2008 (6)
- February 2008 (5)
- January 2008 (6)
- December 2007 (5)
- November 2007 (5)
- October 2007 (7)
- September 2007 (2)
- August 2007 (7)
- July 2007 (4)
- June 2007 (3)
- April 2007 (1)
Michael Bleigh