How to remove '/' from end of Sinatra routes

Viewed 224

I'm using Sinatra and the shotgun server.

When I type in http://localhost:9393/tickets, my page loads as expected. But, with an extra "/" on the end, Sinatra suggests that I add

get '/tickets/' do

How do I get the server to accept the extra "/" without creating the extra route?

The information in Sinatra's "How do I make the trailing slash optional?" section looks useful, but this means I would need to add this code to every single route.

Is there an easier or more standard way to do that?

My route is set up as

get '/tickets' do
2 Answers

This question is actually bigger than it appears at first glance. Following the advice in "How do I make the trailing slash optional?" does solve the problem, but:

  • it requires you to modify all existing routes, and
  • it creates a "duplicate content" problem, where identical content is served from multiple URLs.

Both of these issues are solvable but I believe a cleaner solution is to create a redirect for all non-root URLs that end with a /. This can easily be done by adding Sinatra's before filter into the existing application controller:

before '/*/' do
  redirect request.path_info.chomp('/')
end

get '/tickets' do
  …
end

After that, your existing /tickets route will work as it did before, but now all requests to /tickets/ will be redirected to /tickets before being processed as normal.

Thus, the application will respond on both /ticket and /tickets/ endpoints without you having to change any of the existing routes.

PS: Redirecting the root URL (eg: http://localhost:9393/ → http://localhost:9393) will create an infinite loop, so you definitely don't want to do that.

Related