Setting up Custom Redirects in a Rails Application
Explore the different ways that you can implement custom redirects for routes in a Rails application.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

In this last video about routes, we are going to add some custom routes that I think you'll find pretty handy.

How to do a redirect

First, I'm going to show how to do a redirect. In this example, I want to redirect a page to my personal blog, so I type:

# config/routes.rb

get "blog", to: redirect("http://jordanhudgens.com")

large

Essentially, this command will redirect anyone going to localhost:3000/blog to jordanhudgens.com.

How to create an error 404 pages

To add the error page, go to the bottom of your routes file and add:

# config/routes.rb

get "*path" to: redirect ("/error")

This error page route has to be placed only at the bottom as you don't want every route to be send to it.
If you notice, we don't have anything called /error. So, go to the controller file and add a new method called error.

# app/controllers/posts_controller.rb

def error
end

We don't have to add anything else because we are not passing any values through it.

medium

Next, go back to your routes folder and add the route for error:

# config/routes.rb

get "error", to: "pages#error"

This is how your routes file looks like:

large

Next, go the views/pages folder and create a new file called error.html.erb and write the content you want. I'm going to write

<h1>Sorry, that page does not exist</h1>

If you want the user to get redirected to your home page, you can add the home page route directly to your code.

Go back to <%= link_to "homepage", root_path %>

large

This code means link_to is going to create a link to the home page and root_path is the route of the application. If you want to know the route, go to Rails console and type
rake routes and this will display all the routes.

large

At the bottom, you can see the root Prefix is mapped to your home page. To test this, go to your browser and type any route other than the ones we have. For example, I type localhost:3000/yahoo and I will get the error page.

medium

Notice that the home page that we put in has automatically become a link. Click on it and get sent back to the home page.