Silex Routing vs Trailing Slashes

In Silex-based projects I always define my routes with a trailing /. When defining a route with a trailing slash, the router will respond to both the route without and with slash:

  • $app->get('/hello', …); will respond to http://localhost/hello but not to http://localhost/hello/
  • $app->get('/hello/', …); will respond to http://localhost/hello and to http://localhost/hello/

Unfortunately this only works for GET routes. To make other methods work graze/silex-trailing-slash-handler comes in handy:

Handle requests missing a trailing slash in Silex by appending a slash and issuing an internal sub-request.

Usage is really simple, as graze/silex-trailing-slash-handler comes with a service provider that takes care of everything.

$app->get('/', function () {
    return 'Hello World!';
})

$provider = new \Graze\Silex\ControllerProvider\TrailingSlashControllerProvider();
$app->register($provider);
$app->mount('/', $provider);

Just remember to define your routes first, before mounting the controller provider.

graze/silex-trailing-slash-handler

Did this help you out? Like what you see?
Consider donating.

I don’t run ads on my blog nor do I do this for profit. A donation however would always put a smile on my face though. Thanks!

☕️ Buy me a Coffee ($3)

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.