Redirect response from Event Subscriber in Symfony PHP

Viewed 5104

I'm trying to return a permanent (301) redirect response from a event subscriber hooked into the kernel events in Synfony PHP.

My subscriber is as follow:

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

use Symfony\Component\HttpFoundation\RedirectResponse;

class KernelSubscriber implements EventSubscriberInterface {

    public function __construct() {

        // some stuff here but not relevant for this example
    }

    public static function getSubscribedEvents(): array {

        return [ KernelEvents::REQUEST => 'onRequest' ];
    }

    public function onRequest(GetResponseEvent $event): void {

        // if conditions met
        //     301 redirect to some internal or external URL

        if(!$event->isMasterRequest()) return;
    }   
}

If this were a controller I would return $this->redirectToRoute('route') or something like that but returning from the onRequest method is in a much different context.

How can I return a response (a redirect, in particular) from this event subscriber?

3 Answers

Should be something like:

$event->setResponse(new RedirectResponse($route));

In my case the event had no setResponse method, but I could use the send method from the Response class.

$response = new RedirectResponse('https://stackoverflow.com/', 302);
$response->send();

Use the below method to set the redirect response / redirect url.

$event->setController(function() use ($redirectUrl) {
    return new RedirectResponse($redirectUrl);
});
Related