Rails3 middleware for redirecting old urls

Rails3 middleware for redirecting old urls

Yesterday I deployed my new Frick-Web 4.0 website. In the context of the refactoring of my website I restructured my database in some cases. For that reason a few of my URLs changed and I have to be mindful of not loosing my google ranking and my URLs. So I decided to write a Rails middleware. This middleware handels all my redirecting, if old URLs gets called.

My middleware:

class OldUrlRedirector

  def initialize app
    @app = app

  def call env
    if env["PATH_INFO"] =~ /^regex-matches-old-url/ # e.g.: /^\/page\/projekte/
      new_path = "/new-url" # e.g. : "/projects"
      header = {}
      header["Location"] = new_path
      status = 301
      response = ["This resource has permanently moved to #{new_path}"]
      status, header, response =
    [status, header, response]

Do not forget to include the middleware in the autoload path, I did it this way (config/application.rb):

%w(middleware).each do |dir|
  config.autoload_paths << "#{config.root}/app/#{dir}"

When the middlware is in the autoload path, you have to take care that it is loaded in the correct order. I backuped that with an initializer (config/initializers/old_url_redirector.rb):

Rails.application.config.middleware.insert_before(0, OldUrlRedirector)
Matthias Frick
Ruby on Rails
0 Kommentare

Über den Autor

Matthias Frick
Matthias Frick, MSc.

Er ist ein langjähriger Ruby-on-Rails Entwickler und leitet das Unternehmen Frick-Web.

0 Kommentare zu "Rails3 middleware for redirecting old urls"

Kommentar verfassen