ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# # 以 / 结尾的路由模式 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) ~~~