Permalink
Browse files

add RedirectHost middleware as example

  • Loading branch information...
1 parent 3026b0b commit 37d0e8d7e9d60f82d9c21ea7362790790567872d @alexch committed Dec 9, 2010
Showing with 44 additions and 0 deletions.
  1. +44 −0 rack/redirect_host.rb
View
@@ -0,0 +1,44 @@
+# A Rack middleware component that redirects from old host to new host.
+#
+# To use, put
+# use RedirectHost, :from => "www.foo.com", :to => "foo.com"
+# in your Rack config or Sinatra app.
+#
+# :from can be multiple hosts, comma-delimited. e.g.
+# :from => "www.foo.com,foo.heroku.com"
+#
+class RedirectHost
+ def initialize(app, options = {})
+ @app = app
+ @options = options
+ end
+
+ def from_hosts
+ options[:from].split(",")
+ end
+
+ def to_host
+ options[:to]
+ end
+
+ def call(env)
+ if from_hosts.include?(env['SERVER_NAME'])
+ destination = "#{env['rack.url_scheme']}://#{to_host}"
+ destination << ifblank(env['PATH_INFO'], '/')
+ destination << "?#{env['QUERY_STRING']}" unless env['QUERY_STRING'].empty?
+
+ [301, {'Location' => destination}, ["redirecting to <a href='#{destination}'>#{destination}</a>"]]
+ else
+ @app.call(env)
+ end
+ end
+
+ def ifblank(s, default = "")
+ if s.blank?
+ default
+ else
+ s
+ end
+ end
+
+end

0 comments on commit 37d0e8d

Please sign in to comment.