How to create canonical routes in Rails applications

Canonical routes are used to ensure that search engines and users access content through a consistent URL. They play an essential role in web development, redirecting incoming requests to a desired URL. They ensure that all versions of the URL point to the same predefined URL to avoid duplication.

Syntax for canonical routes

Here is the syntax for adding canonical routes in a Rails application:

get "/canonical-route", to: redirect('/original-route')
Syntax for using canonical routes
  • /canonical-route: This is the route that needs to be redirected to the desired path.

  • /original-route: This is the actual route where we are redirected when the /canonical-route is accessed through the browser.

Example

Let’s take an example of a demo Rails application where the /home path points to the home page of the application. Now, we want to redirect the /homepage path to the same home page. This is the use case where canonical routes come into action.

Code

Click the “Run” button to execute the code below:

//= link_directory ../stylesheets .css
//= link_tree ../../javascript .js
Implementing canonical routes in a Rails application

In the above example, the /home path in the URL redirects us to the home page of the application. If we use the /homepage instead of /home in the URL, it will again redirect us to the same home page.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved