July 02, 2024
How to Redirect Incoming HTTP Requests Using Rails Router
This post is part of my handbook on the Rails Router.
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: 302Note: 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/")
Subscribe to get future posts via email (or grab the RSS feed)