我在Slim应用程序中有这条路线:
$app->get('/fasi/:id/',function ($id) use ($app) {
$app->render("fasi.html");
});
这回答了
http://test/fasi/1/
还要
http://test/fasi/1
有没有办法强制Slim只回复带有斜杠(第一个)的url,或者重定向客户端添加尾部斜杠?
答案 0 :(得分:4)
您可以选择斜杠和参数,如下所示:
$app->get('/fasi/[:id[/]]',function ($id) use ($app) {
$app->render("fasi.html");
});
这适用于:
或:
答案 1 :(得分:0)
您可以使尾随斜杠可选
$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 +尾部斜杠,请记住,这将重定向所有URL以添加尾部斜杠
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ http://domain.com/$1/ [L,R=301]
答案 2 :(得分:0)
如果要将所有以/结尾的URL重定向/重写为非跟踪/等效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);
});
答案 3 :(得分:0)
$app->get('/fasi/{id[0-9]*}{slash:[/]?}',function ($id) use ($app) {
$app->render("fasi.html");
}
尝试一下。
答案 4 :(得分:-1)
这就是我对基于框架的基于框架的应用所做的事情
//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);
});