[英]How to disable trailing slash redirect in Symfony 4.1?
如果您知道以斜杠结尾的每条路线都应生成404,则只需定义一条路线即可:
/**
* @Route("{anything}/")
*/
public function routeWithTrailingSlashAction()
{
throw new ResourceNotFoundException();
}
我认为可能会有更合适的方法来做到这一点,但是我认为它至少应该作为一个临时解决方案。
为了改善NicolasB的答案,我想在单个EventSubscriber中检查每个请求的斜杠就可以解决问题。 虽然仍然有些偷偷摸摸,但对我来说,此解决方案似乎更易于维护。
@NicolasB的解决方案太笨拙 ,因此我创建了自定义事件侦听器,用于检查所有带有重定向的响应并将其转换为404错误:
<?php
namespace App\EventListener;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class RedirectionListener
{
public function onKernelResponse(FilterResponseEvent $event): void
{
$response = $event->getResponse();
if ($response->isRedirection()) {
throw new NotFoundHttpException();
}
}
}
不要忘记注册:
App\EventListener\RedirectionListener:
tags:
- { name: kernel.event_listener, event: kernel.response }
注意:所有重定向都将转换为404,而不仅仅是尾部斜杠重定向。 您应该牢记这一点。 但是我正在开发API,因此根本不需要任何重定向,因此此解决方案解决了我的问题。
如果您知道更好的解决方案,欢迎再次发表答复!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.