Skip to content

Instantly share code, notes, and snippets.

@gabrieltaylor
Last active October 2, 2018 15:52
Show Gist options
  • Save gabrieltaylor/79b8061cfe1f9dc6556c to your computer and use it in GitHub Desktop.
Save gabrieltaylor/79b8061cfe1f9dc6556c to your computer and use it in GitHub Desktop.
Rewrite trailing slash in Sinatra

To avoid receiving an error when you attempt to access one of your routes and accidentally leave a trailing slash on the URL, you can use Rack::Rewrite to redirect the browser to the same URL without the trailing slash.

First add the gem to your Gemfile

gem 'rack-rewrite', '~> 1.5.0'

Run bundle install

Add

require 'rack/rewrite'

to config/environment.rb

Now add

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

to config/environment.rb

Restart your Sinatra app and test in your browser.

@avdyushin
Copy link

It's easy to make trailing slash optional:

get '/my/path/?' do
end

@23tux
Copy link

23tux commented Nov 13, 2016

But this would lead to duplicate content in search engines, because /my/path and /my/path/ ARE different URLs, so the way to go is to provide a permanent, 301 redirect.

@mwakipesile
Copy link

mwakipesile commented Dec 5, 2016

This can be reasonably taken care of, using before filter:

before(%r{/(.+)/$}) { |path| redirect(path, 301) }

@richiethomas
Copy link

@mwakipesile:

before(%r{/(.+)/$}) { |path| redirect(path, 301) }

This would only work if the original request is a GET request, correct? If the path is associated with a POST request or something, would it fail?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment