Canonical URLs with Rack and Heroku

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

Got 301’d to:

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

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 to

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.

About Jimmy Bogard

I'm a technical architect with Headspring in Austin, TX. I focus on DDD, distributed systems, and any other acronym-centric design/architecture/methodology. I created AutoMapper and am a co-author of the ASP.NET MVC in Action books.
This entry was posted in Ruby. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • Thanks Jimmy. This has been on my list to figure out for a few days now. I can’t believe how easy this stuff is with Sinatra and Heroku.

  • Vijay Santhanam

    Thanks Jimmy, you make Heroku + Ruby + all these libraries sound like a lot of fun.

    Any chance you can open source a demo website so we can see how you’ve set stuff up with all the tech and gems.

  • How to resolve problems running Sinatra 1.0 on Ruby 1.9.2 -p0:

    I’m running Ruby 1.9.2 on Windows 7. When I tried to run through the Hello World example on the sinatra site, I got the following error:

    C:/Ruby192/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:753:in `read’: Invalid argument – (Errno::EINVAL)

    Turns out this is a known issue with Sinatra 1.0 and will be fixed in the next release:

    but in the meantime, you can edit base.rb in

    [ruby 1.9.2 root]\lib\ruby\gems\1.9.1\gems\sinatra-1.0\lib\sinatra

    adding the following line to the CALLERS_TO_IGNORE variable:


    The link above shows exactly where to add it. I added it to mine, and I’m up and running now.

  • thank you jimmy! just saved me hours of trying to figure this out :)