Rack Canonical Host
Rack middleware that lets you define a single host name as the canonical host for your application. Requests for other host names will then be redirected to the canonical host.
Add this line to your application's
And then execute:
Or install it yourself as:
$ gem install rack-canonical-host
For most applications, you can insert the middleware into the
in the root of the application.
Here's a simple example of what the
config.ru in a Rails application might
look like after adding the
require ::File.expand_path('../config/environment', __FILE__) use Rack::CanonicalHost, 'example.com' run YourRailsApp::Application
In this case, any requests coming in that aren't for the specified host,
example.com, will be redirected, keeping the requested path intact.
You probably don't want your redirect to happen when developing locally. One way to prevent this from happening is to use environment variables in your production environment to set the canonical host name.
With Heroku, you would do this like so:
$ heroku config:add CANONICAL_HOST=example.com
Then, can configure the middleware like this:
use Rack::CanonicalHost, ENV['CANONICAL_HOST'] if ENV['CANONICAL_HOST']
Now, the middleware will only be used if a canonical host has been defined.
If you'd like the middleware to ignore certain hosts, use the
use Rack::CanonicalHost, 'example.com', ignore: ['api.example.com']
In this case, requests for the host
api.example.com will not be redirected.
Alternatively, you can pass a block whose return value will be used as the canonical host name.
use Rack::CanonicalHost do |env| case env['RACK_ENV'].to_sym when :staging then 'staging.example.com' when :production then 'example.com' end end
If you want it to react only on specific hosts for multi-domain environment use
it accepts string, regexp or an array.
use Rack::CanonicalHost, 'example.com', if: /.*\.example\.com/ use Rack::CanonicalHost, 'example.ru', if: /.*\.example\.ru/
- Fork it
- Create your feature branch (
git checkout -b my-new-feature)
- Commit your changes (
git commit -am 'Add some feature.')
- Push to the branch (
git push origin my-new-feature)
- Create a new Pull Request
Thanks to the following people who have contributed patches or helpful suggestions:
- Thomas Maurer
- Jeff Carbonella
- Joost Schuur
- Jon Wood
- Peter Baker
- Nathaniel Bibler
- Eric Allam
- Fabrizio Regini
Copyright © 2009-2014 Tyler Hunt.
Released under the terms of the MIT license. See LICENSE for details.