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.
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.