Reputation: 2850
I created a small application with SlimFramework v3 and I am able to build a simple route like this:
// GET localhost/admin
$app->get('/admin', function(){
# code here
});
My problem is that this work only for localhost/admin and not for localhost/admin/ (with final backslash). Is there any option to use ONE route for both?
Upvotes: 0
Views: 44
Reputation: 11135
There are 2 possibilities
Specify an optional /
$app->get('/admin[/]', function(){
# code here
});
Add middleware that redirects routes with an ending /
to the url without that.
use Psr\Http\Message\RequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
$app->add(function (Request $request, Response $response, callable $next) {
$uri = $request->getUri();
$path = $uri->getPath();
if ($path != '/' && substr($path, -1) == '/') {
// permanently redirect paths with a trailing slash
// to their non-trailing counterpart
$uri = $uri->withPath(substr($path, 0, -1));
if($request->getMethod() == 'GET') {
return $response->withRedirect((string)$uri, 301);
}
else {
return $next($request->withUri($uri), $response);
}
}
return $next($request, $response);
});
(Source: http://www.slimframework.com/docs/cookbook/route-patterns.html)
Upvotes: 1