Search code examples
phpsymfonyroutessymfony4

How to disable trailing slash redirect in Symfony 4.1?


I'd like to disable default Symfony 4.1 behavior that redirects users from /foo/ to /foo. What's the best way to disable this behavior? I'm developing API so I don't need these redirects.


Solution

  • @NicolasB's solution is too hacky, so I've created custom event listener that checks all responses with redirects and converts them to 404 error:

    <?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();
            }
        }
    }
    

    Don't forget to register it:

    App\EventListener\RedirectionListener:
      tags:
      - { name: kernel.event_listener, event: kernel.response }
    

    Note: all redirects will be converted to 404s, not only trailing slash redirects. You should keep it in mind. However I am developing API, so I don't need any redirects at all, so this solution solves my problem.

    If you know better solution you're welcome to post another reply!