SW6: Hook into noroute 404 event
With this code snippet you can perform certain actions in Shopware 6 before the 404 error is returned to the user. I use this very often, for example to make redirects from old product urls to the new products, for this I have created the following plugin: https://github.com/Loewenstark/LoewenstarkRedirect-SW6
Here you find the key elements to hook into the 404 event:
src/Resources/config/services.xml
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="Devert\RedirectExample\Storefront\Event\NoRoute">
<tag name="kernel.event_subscriber"/>
</service>
</services>
</container>
src/Storefront/Event/NoRoute.php
<?php declare(strict_types=1);
namespace Devert\RedirectExample\Storefront\Event;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
class NoRoute implements EventSubscriberInterface
{
public function __construct()
{
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::EXCEPTION => 'onKernelException'
];
}
public function onKernelException(GetResponseForExceptionEvent $event): void
{
$exception = $event->getException();
$request = $event->getRequest();
if (!$request)
{
return;
}
if ($exception instanceof NotFoundHttpException)
{
//do what ever you want to do
$response = new RedirectResponse('https://devert.net/', 301);
$event->setResponse($response);
}
return;
}
}