# # 以 / 結尾的路由模式
Slim treats a URL pattern with a trailing slash as different to one without. That is,`/user`and`/user/`are different and so can have different callbacks attached.
> Slim將帶結尾斜杠的URL模式視為與不帶結尾斜杠的URL模式不同。也就是說,`/use`r和`/user/`是不同的,因此可以附加不同的回調。
For GET requests a permanent redirect is fine, but for other request methods like POST or PUT the browser will send the second request with the GET method. To avoid this you simply need to remove the trailing slash and pass the manipulated url to the next middleware.
> 對于GET請求,可以使用永久重定向,但是對于POST或PUT等其他請求方法,瀏覽器將使用GET方法發送第二個請求。要避免這種情況,只需刪除后面的斜杠并將處理后的url傳遞給下一個中間件。
If you want to redirect/rewrite all URLs that end in a`/`to the non-trailing`/`equivalent, then you can add this middleware:
> 如果你想重定向/重寫所有以`/`結尾的url到非尾隨`/`等效,那么你可以添加這個中間件:
~~~
<?php
use Psr\Http\Message\RequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface 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) == '/') {
// permanently redirect paths with a trailing slash
// to their non-trailing counterpart
$uri = $uri->withPath(substr($path, 0, -1));
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](http://github.com/middlewares/trailing-slash)中間件,它也允許您強制將一個尾隨斜杠附加到所有url:
Alternatively, consider[middlewares/trailing-slash](http://github.com/middlewares/trailing-slash)middleware which also allows you to force a trailing slash to be appended to all URLs:
~~~
use Middlewares\TrailingSlash;
$app->add(new TrailingSlash(true));
//true添加結尾的斜杠(false刪除它)
// true adds the trailing slash (false removes it)
~~~
- 開始
- 安裝
- 升級指南
- Web服務器
- 概念
- 生命周期
- PSR 7
- 中間件
- 依賴容器
- 實例 及通知和警告處理
- Request
- 請求方法
- 請求頭信息
- 請求主體
- 上傳的文件
- 請求幫助
- 路由對象
- Response
- 響應狀態
- 響應標頭
- 響應體
- 返回JSON
- 視圖模板
- 路由
- 創建路由
- 路由回調
- 路由策略
- 路線占位符
- 路由名
- 路由組
- 路由中間件
- 路由表達式緩存
- 容器識別解析
- 封裝中間件
- 路由的中間件
- 錯誤處理中間件
- 方法重寫的中間件
- 輸出緩沖中間件
- 內容長度中間件
- 擴展功能
- 以 / 結尾的路由模式
- 獲取當前路由
- 設置CORS
- 使用POST表單上傳文件
- 第三方組件
- slim-session
- auth
- slim-api-skeleton
- dir