Home

Remove trailing slashes from URLs in Rails

A while ago we looked into how search engines deal with pages that serve the same content on a URL that ends in a trailing slash, and without. We found that (for Google at least), they're considered separate pages, which means there's a risk of duplicate content if you allow users to access both domain.com/page and domain.com/page/, without one redirecting to the other.

I realised that Ruby on Rails, the framework that I use for everything I build, by default allows users to access both the trailing slash and non-trailing slash for any URL.

There's a few solutions to this on StackOverflow, but I couldn't find anything that works for Rails 5 or above, which this site is built on.

In your gemfile, add the rack-rewrite gem.

gem 'rack-rewrite'

Then, in config/application.rb, add this:

config.middleware.insert_before(Rack::Runtime, Rack::Rewrite) do
  r301 %r{^/(.*)/$}, '/$1'
end

I found this by updating the recommendation from Steve Grossi.

I wrote more about SEO and Ruby on Rails at the Propellernet blog, and if you want to talk about how to make your Rails site better for search, you can find me on Twitter @davepeiris.

May 2019