I want to redirect all root requests to a /pages/home
url, but I want to keep all the params used in the original request.
So:
http://myserver.com/?param1=value1¶m2=value2
Becomes
http://myserver.com/pages/home?param1=value1¶m2=value2
There are several SO questions about passing params in a redirect
but I haven't found any related to passing request's params.
# routes.rb
root :to => redirect { |params, request| "/pages/home?#{request.params.to_query}" }
Update 1
You can also play with the request.params
to build the new path
:
root :to => redirect { |params, request| "/pages/#{request.params[:page]}.html?#{request.params.to_query}" }
The other answer works but leaves a ?
at the end in case there are no parameters.
This seems to do the trick without the side effects:
root to: redirect(path: '/quick_searches/new')
Hope it helps!
In Rails 5, this can be now be done concisely simply by rewriting ONLY the path component in the redirect (so all original query params will be retained):
# in routes.rb
root to: redirect(path: '/pages/home')
Relevant documentation link:
http://api.rubyonrails.org/classes/ActionDispatch/Routing/Redirection.html
Building on @fguillen's answer for Rails4
You need two lines in routes.rb
# in routes.rb
match "/pages/home", to: 'pages#index', via: :get
match "/", to: redirect{ |params, request| [ "/pages/home", request.env["rack.request.query_string"] ].join("?") }, via: :all
The join on an array also handles the dangling question mark at the end in case there are no parameters.