Lars Pind

internet software, coaching, and entrepreneurship

Lars Pind - internet software, coaching, and entrepreneurship
Check out Coach TV, my video blog on happiness and personal development for geeks.

[Rails] How to do a 301 redirect

November 06, 2005 · 3 comments

I had to dig a little for this. The answer is simply:

1
2
headers["Status"] = "301 Moved Permanently"
redirect_to "/"

Here is the relevant snippet from response.rb in ActionPack:

1
2
3
4
def redirect(to_url, permanently = false)
  @headers["Status"]   = "302 Found" unless @headers["Status"] == "301 Moved Permanently"
  @headers["location"] = to_url
  ...

So as you can see, it actively checks for that particular header. Kinda weird that it doesn’t have a :status flag like so many other methods, but that’s the way it is.

blog comments powered by Disqus

3 responses so far ↓

  • 1 Phil // Jun 11, 2006 at 03:02 AM

    Thanks Lars! This post was definitely just a time saver for me! So ActionPack seems a little broken here -- what's up with that permanently parameter that... doesn't get used?
  • 2 Lars Pind // Jun 12, 2006 at 04:21 AM

    Yeah, seems it was lost in the shuffle when the redirect code was refactored.
  • 3 Stephan Soller // Aug 12, 2006 at 05:01 PM

    Thanks for the hint. I was just about to start digging around. You saved me quite some time.