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.
rack-rewrite to your Gemfile
bundle install from your shell to make it available to your project.
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.