Rails 5.2 adds allow_other_host to redirect_back method

Mohit Natoo

Mohit Natoo

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.


> request.host
#=> "http://www.bigbinary.com"

> request.headers["Referrer"]
#=> "http://www.google.com"

# This will redirect back to google.com
redirect_back(fallback_path: "/")

# This will not redirect back to google.com
redirect_back(fallback_path: "/", allow_other_host: false)

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.