NoobOnRails

Ruby on Rails tips, tricks and hints for the aspiring rails hero.



Monday, August 21, 2006

Redirecting with Mongrel


This took me a minute to figure but with the great folks at Mongrel support (ie Zed), it was a piece of cake. This is the script I stuck in a file called, mongrel.conf in my railsapp/log folder on my production server.


class RedirectHost < Mongrel::HttpHandler

def process(request, response)
if request.params["HTTP_X_FORWARDED_HOST"] == "DOMAIN.com"
response.start(302,true) do |head, body|
head["Location"] = "http://www.DOMAIN.com/"
head["Content-type"] = "text/html"
body.write("Please go here instead: www.DOMAIN.com")

end
end
end

end

uri "/", :handler => RedirectHost.new, :in_front => true



What this script is basically saying is that if the incoming HTTP request begins with just "domain.com", redirect it to "http://www.domain.com". In my if statement, I had to use request.params["HTTP_X_FORWARDED_HOST"] becuase I'm on a shared host which puts me behind a proxy. If you try this script and it's not working, stick

puts request.params.inspect

under the body.write line and above that first end, save it, stick it on your server, restart mongrel
and try hitting your site again. It still won't work, but you'll get some more information in your
mongrel.log file. From that extra info, you should be able to see if you need to use
"HTTP_X_FORWARDED_HOST" or just "Host". You can see my redirecting in action over at http://cookmor.com
(that'll redirect to http://www.cookmor.com)


UPDATE: I thought i would mention how you start mongrel to load that script. The mongrel.conf sits in your railsapp/log folder so, from your RailsApp folder, start mongrel with with this:

mongrel_rails start -e production -p YOURDESIREDPORT -d -S log/mongrel.conf

0 Comments:

Post a Comment

<< Home