Rails 5.2 adds allow_other_host to redirect_back method

Mohit Natoo

By Mohit Natoo

on May 30, 2018

Rails 5.0 had introduced redirect_back method to perform redirection to path present in HTTP_REFERRER. If there is no HTTP_REFERRER present, then site is redirected to fallback_location.

Now consider the following scenario.

In one of the searches on google.com, we see a link to bigbinary.com. On clicking the link, we are navigated to bigbinary.com.

When somebody gets redirected to bigbinary.com from google.com, the HTTP REFERRER is set to google.com

If bigbinary.com uses redirect_back in its code then the user will get redirected to google.com which might be undesired behavior for some applications.

To avoid such cases, Rails 5.2 has added a flag allow_other_host to not allow redirecting to a different host other than the current site.

By default, allow_other_host option is set to true. So if you do not want users to go back to google.com then you need to explicitly set allow_other_host: false.

1
2> request.host
3#=> "http://www.bigbinary.com"
4
5> request.headers["Referrer"]
6#=> "http://www.google.com"
7
8# This will redirect back to google.com
9redirect_back(fallback_path: "/")
10
11# This will not redirect back to google.com
12redirect_back(fallback_path: "/", allow_other_host: false)
13

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.