如何在 Symfony 4.1 中禁用尾部斜杠重定向?

How to disable trailing slash redirect in Symfony 4.1?

我想禁用将用户从 /foo/ 重定向到 /foodefault Symfony 4.1 behavior。禁用此行为的最佳方法是什么?我正在开发 API,所以我不需要这些重定向。

如果您知道每条以尾部斜杠结尾的路由 都应该生成 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,所以我根本不需要任何重定向,所以这个解决方案解决了我的问题。

如果您知道更好的解决方案,欢迎您post再次回复!