Redirect old URLs in Rails

February 15th, 2007 by Trevor

I'm in the process of porting over a PHP site to Rails, but I don't want to break any old links. The way things work now, the URL to view a particular topic would be something along these lines:

http://example.com/view.php?id=1

I'd like these to redirect the user to the appropriate topic, and I'll be maintaining the id value when moving everything over to the new database. So, it turns out that catching all of these PHP-style links and forwarding them over to the new system is pretty easy.

I started by adding a catchall bit in my routes.rb like so:

map.catch_all "*path", :controller => "topics",  :action => "unknown_request"

Then, I threw together an unknown_request action in my topics_controller.rb:

def unknown_request
  if request.request_uri.include?('view.php')
    redirect_to topic_path(:id => params[:id])
  else
    redirect_to topics_path # or some other path
  end
end

Easy as pie! Plus, I can add elsif statements ad nauseam if I need to catch other deprecated URLs.

Hope this helps somebody save some time out there on the Internets. I found a couple other posts about this, but this technique seems pretty straightforward. Feel free to comment if you know of a better way!

Comments

Posting code? Please use Pastie.

Have a question? Please visit the Forum.

1 Comment

  1. I would suggest to

    def old_action
    headers["Status"] = “301 Moved Permanently”
    redirect_to “http://www.new-url.com/”
    end

    It’s more SEO friendly.

    Comment by ynw on August 28, 2007

Forum

El Dorado

Looking for Work?

LifeSnapz is Hiring