Kevin Dark
Kevin Dark

Reputation: 2149

How do I redirect from a page that no longer exist Rails 4

I created a blog with a post model and posts controller. Later I decided to update the posts resource in my routes to use blog as the path. Earlier today I took a look at how my site was indexed on Google and noticed mysite.com/posts is still indexed and goes to the 404 page. I'm having trouble determine how I could redirect this to the new blog path. Any guidance you can provide would be greatly appreciated. If it is necessary to answer this question, I included my routes below.

 resources :posts, :path => 'blog' do
end

 root "pages#home"
end

Upvotes: 0

Views: 78

Answers (2)

Wizard of Ogz
Wizard of Ogz

Reputation: 12643

If you need to handle the redirection at tthe application level then it is pretty easy to do so. Take a look at the examples here.

The following route should add the redirect needed for the specific case you mention.

get '/posts', to: redirect('/blog')

You may also want to handle redirects for the other resourceful routes, depending on how your site is indexed.

get '/posts/new', to: redirect('/blog/new')
get '/posts/:id', to: redirect {|path_params, req| "/posts/#{path_params[:id]}" }
get '/posts/:id/edit', to: redirect {|path_params, req| "/posts/#{path_params[:id]/edit}" }

Upvotes: 1

Raindal
Raindal

Reputation: 3237

I would not recommend doing it with Rails. You would get two different paths leading to the same resources which crawling engines do not really appreciate (/posts/1 and /blog/1 would lead to the same post for instance, wich is not SEO friendly and would probably lead to your website being poorly indexed).

Instead you could answer with a 301. This is a configuration you'll have to do in your Apache/Ngninx/Whatever settings, read more about it here: https://support.google.com/webmasters/answer/93633

Upvotes: 1

Related Questions