Read more

Rails: Default HTTP status codes when redirecting

Henning Koch
May 12, 2022Software engineer at makandra GmbH

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

From controllers

Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

When redirecting from a controller Show archive.org snapshot , the default status code is 302 Found (aka Moved Temporarily):

redirect_to posts_url # HTTP 302 Moved Temporarily

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

redirect_to posts_url, status: 301

From routes

When redirecting from your config/routes.rb Show archive.org snapshot , the default status code is 301 Moved Permanently:

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

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

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

Note

By default Show archive.org snapshot 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.

Posted by Henning Koch to makandra dev (2022-05-12 09:34)