skip to Main Content

For SEO purpose, I have to redirect bunch of urls (something like 200) for now, maybe more later, maybe less.
I want to have easy access to it. So I thought about having a dedicated file containing all urls I need to redirect.
Something like

# config/seo_redirection_table.yml

- old_path: '/old/path/1'
  new_path: '/new_path_1'
  status: 301 
- old_path: '/old/path/2'
  new_path: '/new_path_2'
  status: 301 

And then in my routes.rb mapping this file at the very top.
Is it a good practice ? What do you think ? And how can I handle this logic in my routes.rb.

2

Answers


  1. You could do it in routes.rb like so:

    get '/old/path/:id', to: redirect('/new_path_%{id}', status: 301)
    

    So you don’t need to create a lot of static routes and one test will be enough instead to write tests for the static routes.

    Login or Signup to reply.
  2. If you’d like to have your redirect rules within your code base, your approach is fine. Since the rules are static you can load them upon routes creation:

    # config/routes.rb
    
    require 'yaml'
    
    Rails.application.routes.draw do
      redirects = YAML.load_file('config/redirects.yml')
      redirects.each do |rule|
        get rule["old_path"], to: redirect(rule["new_path"], status: rule["status"])
      end
    
      # other routes
    end
    

    You may also consider using a library:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search