Wednesday, January 6, 2010

Redirecting in rack

I had my CV on apache once, with few domains such as misza.co.uk, www.misza.co.uk etc pointing at it which were all redirected by apache's mod_redirect to the cv.misza.co.uk with a few simple lines:


# Rewrite rules
RewriteEngine on
RewriteCond %{HTTP_HOST} !^cv\.misza\.co\.uk [NC]
RewriteCond %{HTTP_HOST} !^$
RewriteRule ^/(.*) http://cv.misza.co.uk/$1 [L,R=301]


Recently I moved it to heroku.com and I didn't have any control over the web server any more.
Fortunately there is Rack - interface between web server and my small sinatra cv application. It looked like the best place to put redirection logic. Here is a piece of rack middleware doing it.


module Rack
# Redirects to correct domain
class RedirectToDomain

HOST = 'example.com'

def initialize(app)
@app = app
end

def call(env)
req = Rack::Request.new(env)

# localhost for local development
if req.host == HOST or req.host == 'localhost'
@app.call(env)
else
res = Rack::Response.new
res.redirect("http://#{HOST}/")
res.finish
end
end
end
end


To use it with your application require the file above and add


use Rack::RedirectToDomain


in the same way as you would use any other rack middleware. And then the magic happens and you have redirection working without polluting your app with this low level redirection stuff.

You can clone the code on github.

1 comment:

  1. rack-domain_redirect gem does exactly that.

    ReplyDelete