Skip to content

Instantly share code, notes, and snippets.

@georgeguimaraes
Forked from tylerhunt/gist:206213
Created November 18, 2009 02:33
Show Gist options
  • Save georgeguimaraes/237502 to your computer and use it in GitHub Desktop.
Save georgeguimaraes/237502 to your computer and use it in GitHub Desktop.
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 :url
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment