Pregunta

I'm trying to redirect to an external URL in a custom controller whenever I land on the 404 page.

Right now I alter the controller destination in a route subscriber like this:

public function alterRoutes(RouteCollection $collection) {
  if ($route = $collection->get('system.404')) {
    $route->setDefaults([
      '_controller' => '\Drupal\test\Controller\TestController::test',
    ]);
  }
}

This is my controller:

public function test() {
  return new TrustedRedirectResponse('https://google.com', 307);
}

Right now my controller redirects to the frontpage when I try to redirect.

I could fix this problem by calling $response->send() but that is not a good idea since I'm bypassing the http-kernel call stack that way.

How can I redirect from the 404 page?

¿Fue útil?

Solución

With the help from @4k4 I found a solution.

I created an event subscriber that extends the HttpExceptionSubscriberBase class. There I created the redirect like this:

public function on404(GetResponseForExceptionEvent $event) {
  $response = new TrustedRedirectResponse('https://google.com', 307);
  $event->setResponse($response);
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a drupal.stackexchange
scroll top