301 Redirects in Rails

If you’ve ever searched for how to do a 301 redirect in Rails, you’ve probably seen this code:

headers["Status"] = "301 Moved Permanently"
redirect_to "http://www.domain.com/" 

However, after doing some testing (thanks rspec!), I found that the above snippet does not work. Instead, it sends a 302 temporary redirect, which, of course, has an entirely different meaning for the search engines visiting your site.

Apparently, somewhere along the way, Rails stopped honoring the explicit Status header when using redirect_to. To achieve the correct result, you must now use:

head :moved_permanently, :location => "http://www.domain.com/"

To make things nicer, I added the following function to my application.rb file:

def perm_redirect_to(options)
   url = case options
         when String
           options
         else
           url_for(options)
        e end
   head :moved_permanently, :location => url
end
blog comments powered by Disqus