Canonical URLs with Rack and Heroku


In my Heroku/Sinatra adventures, I wanted to make sure that I enforced canonical URLs.  That is:

foo.com

Got 301’d to:

www.foo.com

This helps with SEO optimization, because you don’t want 80 different ways to get to the same content.  With Heroku, this is a snap, as Heroku supports Rack modules.  Lo and behold, google found me this great post on using a simple Rack module, ForceDomain, to do this.

I just followed the instructions on the site, fixed my config.ru:

require 'hello'
require 'rack/force_domain'
use Rack::ForceDomain, ENV["DOMAIN"]
run Sinatra::Application

A git push later and I was finished.  Permanent 301 redirects to enforce canonical URLs from foo.com to www.foo.com.

Of course, the ForceDomain code is up on GitHub if you’re interested in peaking behind the covers.  Naturally it’s like 6 lines of Ruby code, the rest being the Rack/Gems stuff.

Sinatra and Heroku: the elevator pitch