Boom100100
Boom100100

Reputation: 117

How to remove '/' from end of Sinatra routes

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

Upvotes: 2

Views: 383

Answers (2)

mlibby
mlibby

Reputation: 6734

It looks like the FAQ doesn't mention an option that was added in 2017 (https://github.com/sinatra/sinatra/pull/1273/commits/2445a4994468aabe627f106341af79bfff24451e)

Put this in the same scope where you are defining your routes:

set :strict_paths, false

With this, Sinatra will treat /tickets/ as if it were /tickets so you don't need to add /? to all your paths

Upvotes: 3

UrsaDK
UrsaDK

Reputation: 865

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.

Upvotes: 0

Related Questions