-
-
Save docunext/3659397 to your computer and use it in GitHub Desktop.
Rack middleware to ensure all traffic is served from a canonical domain
This file contains 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
# ensure all requests are served from a canonical top-level-domain | |
# | |
# the following in your config.ru will cause all traffic to stevenwilkin.co.uk to | |
# be redirected to stevenwilkin.com if both domains are served by the same app | |
# | |
# require 'redirect_to_tld' | |
# use RedirectToTLD, 'stevenwilkin.com' | |
# | |
class RedirectToTLD | |
def initialize(app, tld = nil) | |
@app = app | |
@tld = tld | |
end | |
def call(env) | |
if ENV['RACK_ENV'] == 'production' and @tld and env['HTTP_HOST'] !~ /#{@tld}/ | |
[301, {'Location' => Rack::Request.new(env).url.sub(/#{env['HTTP_HOST']}/, @tld), | |
'Content-Type' => 'text/plain'}, ['Redirecting...']] | |
else | |
@app.call(env) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment