middlewares/trailing-slash

中间件用于规范化 URI 路径的尾部斜杠

v2.0.1 2020-12-02 00:06 UTC

This package is auto-updated.

Last update: 2024-08-29 04:36:56 UTC


README

Latest Version on Packagist Software License Testing Total Downloads

中间件用于规范化 URI 路径的尾部斜杠。默认情况下会删除斜杠,例如,/post/23/ 转换为 /post/23。如果您在路由器方面遇到问题,则非常有用。

要求

安装

此软件包可以通过 Composer 安装并自动加载,作为 middlewares/trailing-slash

composer require middlewares/trailing-slash

示例

$dispatcher = new Dispatcher([
	(new Middlewares\TrailingSlash(true))
		->redirect()
]);

$response = $dispatcher->dispatch(new ServerRequest());

用法

默认情况下,此中间件会删除 URI 路径的尾部斜杠。将构造函数的第一个参数设置为 true 以添加而不是删除

//Removes the slash, so /post/23/ is converted to /post/23
$slash = new Middlewares\TrailingSlash();

//Force the slash, so /post/23 is converted to /post/23/
$slash = new Middlewares\TrailingSlash(true);

当然,如果路径包含扩展名,则不会添加斜杠。例如,images/image.png 保持不变,而不是转换为 images/image.png/

重定向

如果必须转换路径,则此选项将返回一个 301 响应,重定向到新路径。您可以提供 Psr\Http\Message\ResponseFactoryInterface,它将用于创建重定向响应。如果没有定义,将自动使用 Middleware\Utils\Factory

$responseFactory = new MyOwnResponseFactory();

//Simply removes the slash
$slash = new Middlewares\TrailingSlash();

//Returns a redirect response to the new path
$slash = (new Middlewares\TrailingSlash())->redirect();

//Returns a redirect response to the new path using a specific response factory
$slash = (new Middlewares\TrailingSlash())->redirect($responseFactory);

有关最近更改的更多信息,请参阅 CHANGELOG,有关贡献细节的更多信息,请参阅 CONTRIBUTING

MIT 许可证 (MIT)。有关更多信息,请参阅 LICENSE