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')) {
      '_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, 2019 at 18:07

1 Answer 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);
  • 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
    – 4uk4
    Nov 13, 2019 at 16:47