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)

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Unless noted otherwise, the contents of this post are licensed under the Creative Commons Attribution 4.0 License and code samples are licensed under the MIT License

Leave a comment

Your email address will not be published.

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