There are multiple ways to redirect URLs to a different URL in Rails, and they differ in small but important nuances.
Imagine you want to redirect the following URL https://www.example.com/old_location?foo=bar to https://www.example.com/new_location?foo=bar.
Variant A
You can use ActionController::Redirecting#redirect_to in a controller action
class SomeController < ActionController::Base
def old_location
redirect_to(new_location_url(params.permit(:foo)))
end
end
It will redirect with a 302 status code.
If you pass in unpermitted params (e.g. params.slice(:foo) instead of params.permit(:foo)), your redirect will raise instead.
Variant B
You can also use ActionDispatch::Routing::Redirection#redirect in the routes.rb file:
get 'old_location', redirect(path: '/new_location')
This will:
- Redirect with a 301 status code
- It will forward all query parameters to the redirect URL. E.g.
https://example.com/old_location?b=bwill redirect tohttps://example.com/new_location?b=b.
You can achieve the same forwarding of query parameters with variant A as explained here, but please be aware of its security implications.
Both variants have options to change their default behaviour like status codes.
Search engines and redirects
If you have a public facing website that ranks on search engines, choosing the correct redirect code is important. If you decide to change your URL structure and want the search engines to index the new target URL (/new_location?foo=bar) then you should use a 301. You can read more about
how google handles this
Show archive.org snapshot
.