Reroute old content (.html/.php etc.) to Ruby on Rails

html, routes, ruby-on-rails

Solution

You can do this in multiple ways.

The best and most efficient way is to use your front end web server. You can easily setup some configurations in order to redirect all the old URLs to the new ones.

With Apache, you can use `mod_alias` and `mod_rewrite`.

Redirect /XXX/onlyinstance.html /new/path
RedirectMatch ˆ/XXX/dummy([\d])+\.html$ /new/path/$1

This is the most efficient way both for server and client because handled at server level without the need to initialize the Ruby interpreter.

If you can't/wan't take advantage of server settings, you can decide to use Rails itself. Talking about performance, the most efficient way is to use a Rack middleware which is much more efficient than creating a full controller/action.

class Redirector
  def self.call(env)
    if env["PATH_INFO"] =~ %r{XXX/onlyinstance\.html}
      [301, {"Content-Type" => "text/html", "Location" => "http://host/new/path/"}, "Redirecting"]
    else
      [404, {"Content-Type" => "text/html"}, "Not Found"]
    end
  end
end

There is also a Rack plugin called Redirect that provides a nice DLS for configuring redirects using a Rack middleware.

Just a footnote. I won't creating additional routes using `routes.rb` because you'll end up duplicating your site URLs and wasting additional memory.

See also Redirect non-www requests to www urls in Rails

Problem

I have switched to Ruby on Rails and my current problem is to reroute the old contents like `XXX/dummy.html` or `XXX/dummy.php` in RoR. What exactly is the best solution for - isolated content (`XXX/onlyinstance.html`) - content which has a internal structure like `XXX/dummy1.html`, `XXX/dummy2.html` http://guides.rubyonrails.org/routing.html does not explain how to migrate old content. Note: Changing the old links is NOT an option. The website is hosted, it is not my own server. As the domain hasn't changed, the solution to redirect it seems to be unnecessary...there should be a better solution. EDIT: I have found out that the best solution is in fact rerouting it by the way weppos described. So add a .htaccess file in the public directory and write RewriteEngine on Redirect permanent /XXX.php http://XYZ/XXX For whatever reason, RoR did not accept rerouting in routes.rb...while .html/.xml all goes fine, .php does not function. I haven't found out why. Because weppos answer was the best, I will award him a 50 point bounty, but as the others answers are valid, too, I will upvote them. Thank you all

Original source

Related problems