Eric Schaefer

Removing Trailing Slashes from a Rails App on Heroku

Updated: Oct. 10, 2018

I need to redirect those terrible trailing URL slashes on a large project with thousands of articles. Turns out that trailing slash will lead to duplicate content.

The first suggestion is usually to use Apache’s mod_rewrite, however I wanted a server-agnostic way to handle these redirects. Not every project these days is sitting on top of Apache. And in my particular case, I need this to work on Heroku’s very tightly controlled configuration stack.

The solution which worked for me is just including and configuring the rack-rewrite gem.

1. Add rack-rewrite to your Gemfile

gem 'rack-rewrite'

Then rerun bundle install from your shell to make it available to your project.

2. Configure

Rails 4

In config/application.rb:

require "rack/rewrite"


# Rewrite trailing slashes
# goes inside your main Application class
config.middleware.insert_before(Rack::Runtime, Rack::Rewrite) do
  r301 %r{.*(//+.*)+}, ->(match, env) { match.to_s.gsub(%r{//+},"/") }


An older version of this article included a regular expression which opened up Rack to a URL redirect vulnerability which was pointed out to me by a reader (thanks Joseph!). I have updated the code snippet accordingly.