【问题标题】:Symfony redirect all routes ending with on urlSymfony 重定向所有以 on url 结尾的路由
【发布时间】:2018-05-07 08:11:40
【问题描述】:

在我的 Symfony 项目中,让我们假设我们有以下路线:

$route= new Route('/my-method',array(
    '_controller'=>'AppBundle:MyController:myMethod'
));
$collection->add('my_method_route',$route);

$route= new Route('/my-method2',array(
    '_controller'=>'AppBundle:MyController:myAnotherMethod'
));
$collection->add('my_method2_route',$route);

$route= new Route('/anotherStuff',array(
    '_controller'=>'AppBundle:MyController:anotherStuff'
));
$collection->add('another_stuff',$route);

$route= new Route('/anotherStuff/{param}',array(
    '_controller'=>'AppBundle:MyController:anotherStuffOneParam'
));
$collection->add('another_stuff',$route);

$route= new Route('/anotherStuff/{param}/{another_param}',array(
    '_controller'=>'AppBundle:MyController:anotherStuffTwoParam'
));
$collection->add('another_stuff',$route);

我想要一个以/ 结尾的网址,例如。 http//example.com/my-method/ 重定向到http//example.com/my-method

所以我在考虑是否可以使用正则表达式作为路由的第一个参数,或者配置 Symfony 的路由系统 showhow 以执行重定向。

但是 Symfony 是否可以接受正则表达式或 url 上的可选部分,它可以被输入?例如,使用'/my-method2/?' 来告知路线可能以/ 结尾,而忽略这些内容。

【问题讨论】:

  • 你甚至可以通过一些配置在 web 服务器级别做到这一点:你根本不需要 symfony。

标签: php symfony routes symfony-3.3


【解决方案1】:

您想将所有以斜杠结尾的 url 重定向到相同的 URL 没有权利?

您必须创建一个匹配 .*/$ 的路由,然后在控制器中删除此“/”。

还有一篇文章给出了 symfony doc 上的代码: https://symfony.com/doc/current/routing/redirect_trailing_slash.html

【讨论】:

  • 由于某种原因,在重定向网址中添加了 2 个斜杠。
  • 您是否将路线放在所有路线定义的末尾?这段代码: $url = str_replace($pathInfo, rtrim($pathInfo, ' /'), $requestUri);删除尾部斜杠并替换 URL 中的此部分。最后有两个“/”似乎很奇怪。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-17
  • 2021-11-23
  • 2017-06-02
  • 2014-05-16
  • 2011-10-11
  • 2018-11-06
  • 1970-01-01
相关资源
最近更新 更多