Rails 301 Redirection

Dru picture Dru · Apr 7, 2012 · Viewed 17.6k times · Source

I would like to redirect multiple entries to my landing page to one url.

The following urls, http://mysite.com and http://www.mysite.com, would redirect to http://www.mysite.com/ using 301 redirection. How can/should this be done in Rails?

Answer

Vapire picture Vapire · Apr 7, 2012

I didn't try this, but something like this should work:

class ApplicationController < ActionController::Base
  before_filter :correct_domain!

  private
  def correct_domain!
    unless request.host == 'www.mysite.com'
      redirect_to root_url, :status => 301  # or explicitly 'http://www.mysite.com/'
    end
  end
end

But I'm not sure if the trailing slash is present in the host attribute...