How to Redirect Requests

The redirect helper method lets you redirect any path to another path or URL. For example, the following route redirects all the incoming requests on /images to /photos.

get "/images", to: redirect("/photos")

# OR

get "/images" => redirect("/photos")

If the older route contained dynamic segments, you can reuse them with interpolation, as follows:

get "/images/:tag", to: redirect("/photos/%{tag}")

By default, the Rails router uses HTTP status 301 Moved Permanently for redirecting.

The HyperText Transfer Protocol (HTTP) 301 Moved Permanently redirect status response code indicates that the requested resource has been definitively moved to the URL given by the Location headers. A browser redirects to the new URL and search engines update their links to the resource. - MDN

To change the response status code, pass the :status option.

get "/images/:tag", to: redirect("/photos/%{tag}"), status: 302

Note: Rails will use the default host if you don't provide one. To redirect to an external URL, provide the complete URL, including the host name.

get "/blog", to: redirect("https://www.writesoftwarewell.com/")

If you have any questions or feedback, didn't understand something, or found a mistake, please leave a comment below or send me an email. You can also subscribe to my blog to receive future posts via email.