How to Redirect Incoming HTTP Requests Using Rails Router

1 min read
💡
This post is part of my handbook on the Rails Router.
The Rails Router
Everything you need to know about the incredible routing system in Rails.

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/")

That's a wrap. I hope you found this article helpful and you learned something new.

As always, 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. I reply to all emails I get from developers, and I look forward to hearing from you.

If you'd like to receive future articles directly in your email, please subscribe to my blog. Your email is respected, never shared, rented, sold or spammed. If you're already a subscriber, thank you.