Reputation: 33755
So I have a URL that was generated from an old CMS that I am migrating away from. What I want to do, is rather than supporting the old URL structure, just do a permanent 301 redirect to the new one.
But the only way to know the new one is if the title is the same/similar.
So I have no idea if this is even possible, but here are some examples of what the URL differences:
====== OLD =======
http://www.example.com/rbt/26741-pnpyo-saddened-at-passing-of-roger-clarke.html
====== NEW =======
http://www.example.com/pnpyo-saddened-at-passing-of-roger-clarke
====== OLD =======
http://www.example.com/rbt/26766-algaj-pays-tribute-to-the-honourable-roger-clarke.html
====== NEW =======
http://www.example.com/algaj-pays-tribute-to-the-honourable-roger-clarke
====== OLD =======
====== NEW =======
http://www.example.com/pnp-chairman-expresses-shock-grief-at-clarke-s-passing
So the key differences in the URL structure are the prefix /rbt/12345
where 12345
is some ID, /rbt/
is a static string/directory name, the way the URL was encoded (e.g. it handles apostrophes, etc. horribly) and an extension at the end.
Ideally, it would be nice if my routes.rb
rule could look at each of the above old URL requests and do a permanent 301 redirect to the new and improved URL.
Is this even possible? If so, what might that look like?
Upvotes: 1
Views: 953
Reputation: 78
You will need to set up the redirect (301) in config/routes.rb
# old path
get '/rbt/:name', to: redirect {|path_params, _| "/#{path_params[:name].gsub(/^\d+\-/, '')}" }
# new path
get ':name', to: 'posts#show'
Then ensure that you have a controller (in this case blog), to catch the new redirect.
You can read more here: http://guides.rubyonrails.org/routing.html#redirection
Upvotes: 4
Reputation: 1008
I don't know how many of these URLs do you have or have to redirect but here would be a quick and dirty approach which is only one of the ways you could do it. I would store the old urls in a simple "route table" with the number from the old url and new complete url from new app..
Create a route in routes.rb
get 'rbt/:old_url', to: 'routes_controller#routing'
Then in the RoutesController in your routing methods you do something like this:
def routing
myid = params[:old_url].split('-').first
redirect_to UrlTable.find(myid.to_i).url, :status => moved_permanently
end
I would also add a counter to see how many people still use the old url. I know it's not pretty but sure works.
Upvotes: 0