Last Updated: February 25, 2016
·
3.561K
· mrreynolds

Dealing with trailing slashes in Rails apps

Improve Rails' HTTP manners by either appending or removing trailing slashes in generated URIs.

By default the routes Rails generates are accessible with or without trailing slashes — that makes every one appear as two separate resources, which is suboptimal for caching purposes. In this how-to we're going to append trailing slashes everywhere:

1) Enforce trailing slashes in generated URIs

# config/application.rb
config.action_controller.default_url_options = { trailing_slash: true }

2) Redirect legacy URIs

# Gemfile

gem 'rack-slashenforce'

Then, run bundle install and register the middleware:

# config/application.rb

config.middleware.use Rack::AppendTrailingSlash