Read more

redirect_to and redirect

September 13, 2023Software engineer at makandra GmbH

There are multiple ways to redirect URLs to a different URL in Rails, and they differ in small but important nuances.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show snapshot

Imagine you want to redirect the following url to

Variant A

You can use ActionController::Redirecting#redirect_to in a controller action

class SomeController < ActionController::Base
  def old_location

This will:

  • It will redirect with a 302 status code
  • It will raise ActionController::UnfilteredParameters if there is any other query param than foo, e.g. This is because url_for will call to_h on ActionController::Parameters, which will raise if there are unpermitted parameters.

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. will redirect to

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.

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 more about how google handles this here Show snapshot .

Further reading

Posted by NiklasH to makandra dev (2023-09-13 18:22)