Canonical Host
Submitted by tylerhunt at 09 Oct 13:12
About
There are often times when you'll need to redirect requests for some domains or subdomains to a single canonical host. This middleware lets you specify the canonical host for your application, and will perform a 301 redirect for all non-canonical requests. One of the most common use cases is to redirect the a subdomain like www to the the root domain, or vice versa.
Usage
In its simplest case, just specify your canonical host.
use CanonicalHost, 'example.com'
You can also pass a block that will be evaluated, and its return value will be used as the canonical host. This is often useful when you're targeting multiple environments.
use CanonicalHost do
case Rails.env.to_sym
when :staging then 'staging.example.com'
when :production then 'example.com'
end
end
Code
class CanonicalHost def initialize(app, host=nil, &block) @app = app @host = (block_given? && block.call) || host end def call(env) if url = url(env) [301, { 'Location' => url }, ['Redirecting...']] else @app.call(env) end end def url(env) if @host && env['SERVER_NAME'] != @host url = Rack::Request.new(env).url url.sub(%r{\A(https?://)(.*?)(:\d+)?(/|$)}, "\\1#{@host}\\3/") end end private :urlend