Skip to content
This repository


Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Rack middleware for defining a canonical host name.

branch: master

Fetching latest commit…


Cannot retrieve the latest commit at this time

Octocat-spinner-32 lib
Octocat-spinner-32 .gitignore
Octocat-spinner-32 LICENSE
Octocat-spinner-32 README.rdoc
Octocat-spinner-32 rack-canonical-host.gemspec

Rack Canonical Host

Rack Canonical Host is a bit of Rack middleware that lets you define a single host as the canonical host for your site, and redirect all other hostnames to that canonical host.

In the simplest case, just specify the host name and any requests coming in that aren't for the host will be rewritten with the proper host.

use Rack::CanonicalHost, ''

You could also define a constant in your environment-specific configuration files to set up a canonical host redirect for only certain environments.


Then, you can set up the middle are like this.

use Rack::CanonicalHost, CANONICAL_HOST if defined?(CANONICAL_HOST)

Alternatively, you can pass a block whose return value will be used to set the canonical host.

use Rack::CanonicalHost do
  case ENV['RACK_ENV'].to_sym
    when :staging then ''
    when :production then ''

Rails 3

Using Rack::CanonicalHost in your rails 3 app is pretty straight forward.

Open up your gemfile and add the following. Then 'bundle install' to get the gem.

gem 'rack-canonical-host'

Then create the file config/initializers/canonical_host.rb to capture the configuration block.

Rails.application.config.middleware.use Rack::CanonicalHost do
  case ENV['RACK_ENV'].to_sym
    when :development then '' #make sure this is in your dns or /etc/hosts file
    when :staging then ''
    when :production then ''

You will need to restart your server to have this change take effect.

Copyright © 2009 Tyler Hunt. See LICENSE for details.

Something went wrong with that request. Please try again.