Posted 7 months ago. Visible to the public.

Rails: Default HTTP status codes when redirecting

When redirecting you should take care to use the right HTTP status code.

From controllers

When redirecting from a controller Archive , the default status code is 302 Found (aka Moved Temporarily):

Copy
redirect_to posts_url # HTTP 302 Moved Temporarily

To use a different code, pass a :status option:

Copy
redirect_to posts_url, status: 301

From routes

When redirecting from your config/routes.rb Archive , the default status code is 301 Moved Permanently:

Copy
get '/stories', to: redirect('/articles') # HTTP 301 Moved Permanently

To use a different code, pass a :status option:

Copy
get '/stories', to: redirect('/articles', status: 302)

Note

By default Archive Rails sends a header Cache-Control: max-age=0, private, must-revalidate with all responses, including redirects. That means if you accidentally use a permenent redirect, it is not cached in browsers.

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for unsupported versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2).

Owner of this card:

Avatar
Henning Koch
Last edit:
6 months ago
by Dominik Schöler
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more