pauel February 2016

How to handle trailing slash in nginx?

I have a slim api and an app that always adds slashes at the end of every call. There is no way to change the calls so I search for a way to remove the trailing slashes for all api calls.

How do I do this?

This is what I tried:

rewrite ^/api/(.*)/$ /v1/index.php?$args;

Answers


Rob Allen March 2016

You can use middleware for this.

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) == '/') {
        // remove trailing slash
        $uri = $uri->withPath(substr($path, 0, -1));
        $request = $request->withUri($uri);
    }

    return $next($request, $response);
});

See http://www.slimframework.com/docs/cookbook/route-patterns.html for details.

Post Status

Asked in February 2016
Viewed 3,751 times
Voted 7
Answered 1 times

Search




Leave an answer