Ruby on Rails: Redirecting Non-www to www
September 23, 2011
On a recent project I wanted to make sure the non-www version of the domain redirected to the www version. (I personally always prefer to omit the www as it’s superfluous but hey ho).
The reason for forcing a redirect is so social sharing links such as Twitter “counts” and Facebook “likes” show the correct count, as they treat www. and non-www as different URLS.
Normally, as I use Apache, I just do a rewrite in .htaccess – fairly simple, but as I’m running Ruby as a Mongrel, it bypasses the .htaccess rules so you can’t do it this way.
So, my solution was to do the re-write as a Ruby function. (Ideally, you’d want to do the redirect before you hit your site’s code but I couldn’t find a way).
application_controller.rb:
class ApplicationController < ActionController::Base
before_filter :check_host
#redirect to www version and append uri onto the end
def check_host
if request.host.split('.')[0] != 'www'
redirect_to "http://www." + request.host + request.request_uri
end
end