0

Is it possible to make a "catch all" redirect rule in my routes, for example something like this:

get "/foo*", to: redirect("/bar$1")

Which will result in these 301s:

  • /foo -> /bar
  • /foo/baz -> /bar/baz
  • /foo/?a=b -> /bar/?a=b
John Bachir
  • 22,495
  • 29
  • 154
  • 227

1 Answers1

0

Yes, you can. Here's how I've done this before:

# config/routes.rb    

def get_params_blob_if_present(params)
  "/#{params[:a]}" if params[:a].present?
end

def get_query_string_params_if_present(params, options = {})
  params = params.except(:a) # Don't include blob params
  "?#{params.to_query}" if params.any?
end

MyApp::Application.routes.draw do
  # ...

  get '/foo(/*a)', to: redirect { |params, request| "/foo#{get_params_blob_if_present(params)}#{get_query_string_params_if_present(request.params)}" }

  # ...
end

Basically, (/*a) sets up a blob named a. You can then conditionally include the params from this blob in the redirect URL if any are present. Likewise, you can conditionally include query string params in the redirect URL if any are present.

pdobb
  • 17,688
  • 5
  • 59
  • 74