纤细的斜线路线

Slim trailing slash route

我在 Slim 应用程序中有这条路线:

$app->get('/fasi/:id/',function ($id) use ($app) {
        $app->render("fasi.html");
});

这回答了

http://test/fasi/1/

还要

http://test/fasi/1

有什么方法可以强制 Slim 仅使用尾部斜杠(第一个)回答 url,或者重定向添加尾部斜杠的客户端?

您可以将尾部斜杠设为可选

$app->get('/fasi/:id(/)',function ($id) use ($app) {
    $app->render("fasi.html");
});

或者添加一个重定向到带有尾部斜杠的路由的路由

$app->get('/fasi/:id/',function ($id) use ($app) {
    $app->urlFor('fasi', array('id' => $id));
});

$app->get('/fasi/:id',function ($id) use ($app) {
    $app->urlFor('hello', array('name' => 'Josh'));
})->name('fasi');

或者让 Apache 将您的请求重定向到相同的 url + 尾部斜杠,请记住这将重定向所有 urls 以添加尾部斜杠

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ http://domain.com// [L,R=301]

这就是我对我的基于 slim-framework 的应用程序所做的

//updated code, we do not want .js .css .png to have trailing slash
    $app->add(function (Request $request, Response $response, callable $next) {
    $uri = $request->getUri();
    $files = array('.js','.css','.jpeg','.png','.jpg');
    $path = $uri->getPath();
    foreach ($files as $file) {
        if (strpos($uri, $file) == TRUE) {
            return $next($request, $response);          
        }
        else {
            if ($path != '/' && substr($path, -1) != '/') {
            $uri = $uri.'/';
            return $response->withRedirect((string)$uri, 301);
            }
        }
    }
    return $next($request, $response);
});

您也可以将斜杠和参数设为可选,如下所示:

$app->get('/fasi/[:id[/]]',function ($id) use ($app) {
    $app->render("fasi.html");
});

这适用于:

http://test/fasi/1

或:

http://test/fasi/1/

如果你想redirect/rewrite所有以 / 结尾的 URL 到非尾随 / 等效,那么你可以添加这个中间件:

 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);
    });
$app->get('/fasi/{id[0-9]*}{slash:[/]?}',function ($id) use ($app) {
    $app->render("fasi.html");
}

试试这个。