1

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?

  • 2
    As an aside, redirecting from a 404 may may cause weirdness w/ spiders (eg, Google), especially if you 3xx to another domain. – mpdonadio Nov 13 at 18:07
1

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);
}
  • 2
    OK, the system.404 route is handled very differently from other routes. If you want to redirect on a 404 exception then use a kernel exception subscriber, see drupal.stackexchange.com/a/231166/47547 – 4k4 Nov 13 at 16:47

Not the answer you're looking for? Browse other questions tagged or ask your own question.