路由中的尾随斜杠

Slim 将具有尾部斜杠的 URL 模式视为与没有尾部斜杠的 URL 模式不同。也就是说, /user/user/ 是不同的,因此可以附加不同的回调。

对于 GET 请求,执行永久重定向是合适的,但对于其他请求方法(如 POST 或 PUT),浏览器将使用 GET 方法发送第二个请求。为了避免这种情况,只需删除尾部斜杠,并将处理过的 URL 传递给下一个中间件。

如果你想要重定向 / 重写所有以 / 结尾的 UR L到没有尾部 / 的等效 URL,那么可以添加以下中间件:

<?php
use Psr\Http\Message\RequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
use Slim\Factory\AppFactory;
use Slim\Psr7\Response;

require __DIR__ . '/../vendor/autoload.php';

$app = AppFactory::create();

$app->add(function (Request $request, RequestHandler $handler) {
    $uri = $request->getUri();
    $path = $uri->getPath();

    if ($path != '/' && substr($path, -1) == '/') {
        // 当存在多个斜杠时,递归删除斜杠
        $path = rtrim($path, '/');

        // 将具有尾部斜杠的路径永久重定向到无尾部斜杠的路径
        $uri = $uri->withPath($path);

        if ($request->getMethod() == 'GET') {
            $response = new Response();
            return $response
                ->withHeader('Location', (string) $uri)
                ->withStatus(301);
        } else {
            $request = $request->withUri($uri);
        }
    }

    return $handler->handle($request);
});

或者,考虑使用 middlewares/trailing-slash 中间件,该中间件还允许你强制追加斜杠到所有 URL 的尾部:

use Middlewares\TrailingSlash;

$app->add(new TrailingSlash(true)); // true表示添加尾部斜杠(false表示删除)