Canonical URLs in Rails
Websites often have identical content accessible through multiple URLs. For example:
http://sickpea.com/2009/7/canonical-urls-in-rails http://sickpea.com/2009/7/canonical-urls-in-rails?trackingid=42 http://sickpea.com/2009/7/canonical-urls-in-rails?random=parameter&more=less
A human can quickly (and reasonably) assume that all of these URLs point to the same blog entry, perhaps with minor differences in the formatting or presentation order. Search engines cannot absolutely tell which version is the preferred one, so you either end up with a bunch of duplicate content, or your blog entry appears in search engine listings under an obscure URL.
Google introduced a canonical link standard in February 2009 that hints strongly to the search engine what the preferred URL is. Yahoo, Microsoft, and Ask also immediately supported it. Some people think this little line is a big deal:
<head> ... <link rel="canonical" href="/the-preferred-url-for-this-page" /> ... </head>
It just takes a few lines of code to implement it in your Rails app:
app/controllers/application_controller.rb
# Specify the canonical URL for a page / resource. # def canonical_url(canonical_url) @canonical_url = canonical_url end
app/helpers/application_helper.rb
# Embed canonical link URL, if specified by controller. # http://googlewebmastercentral.blogspot.com/2009/02/specify-your-canonical.htm # def canonical_link_tag tag(:link, :rel => :canonical, :href => @canonical_url) if @canonical_url end
app/views/layouts/application.html.haml
!!! 1.0 %html{ html_attrs } %head = canonical_link_tag ...
When an article is shown, the canonical URL is explicitly set by the controller's action:
app/controllers/articles_controller.rb
class ArticlesController < ApplicationController def show @article = Article.find(params[:id]) canonical_url(article_url(@article)) end ...