Created
March 28, 2012 19:41
-
-
Save latortuga/2229830 to your computer and use it in GitHub Desktop.
Canonical Host Rails Middleware
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# config/application.rb | |
module YourApplication | |
class Application < Rails::Application | |
config.autoload_paths += %W(#{config.root}/lib) | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# lib/canonical_host.rb | |
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# config/environments/production.rb | |
require File.expand_path('../../../lib/canonical_host.rb', __FILE__) | |
YourApplication::Application.configure do | |
config.middleware.use CanonicalHost, 'www.yourdomain.com' | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment