How to route old blog urls to new 301 redirect for seo in routes.rb and using controller

    To do this: Put Following code in routes.rb
      ActionController::Routing::Routes.draw do |map|
        blogs = BlogPost.all.collect{|p| p.cached_slug}.join("|")
        unless blogs.blank?
          map.connect ':id', :controller => 'redirect', :action => 'index', :requirements => { :id => Regexp.new(blogs) }
        end
      end

    It redirects only when path matches with old blog post paths
    Create a controller redirect have following code
    class RedirectController < ApplicationController
      helper_method :check_blog, :check_pages
      def index
        if check_blog
          redirect_to check_blog
        else
          redirect_to root_url
        end
      end
      def check_blog
        conn = ActiveRecord::Base.connection
        id = params[:id]
        sql = "SELECT count(id) as cnt FROM blog_posts WHERE cached_slug='#{id}'"
        res = conn.execute(sql)
        result = res.fetch_row.first
        if result != "0"
          return "/blog/" + id
        else
          return false
        end 
      end

    end

    where cached_slug contains old urls that is to be redirected to new one it match and send proper redirection
    5
    Average: 5 (1 vote)