I Created a site and URL that returns a 404 Not Found status on www.xyz.com This creates a loss of link equity to the domain and negatively impacts the ability to compete in organic search results.

I wanted to Redirect the URLs returning a 404 status to the defined closest alternative, or parent category, to reclaim link equity from external domains.

Example: Suppose I am using URL http://www.mysite.com/about/xyz/ and it return 404 so I wanted to create any module or system that smartly redirect to nearest parent path like "http://www.mysite.com/about/"

I am not able to find any specific documentation which would point me in the right direction.

  • Search 404 module?
    – Kevin
    Commented Jun 21, 2021 at 19:28
  • @Kevin Thanks for your comment actually it's a nice idea I tried that module but it does not fulfill my Exact requirement. Commented Jun 22, 2021 at 5:37

1 Answer 1


Try creating a custom event subscriber. If the page is 404, grab the original URL and redirect accordingly.

To do so, create a new module ("response_test" in this example), with the usual .info.yml and .module file.

Then register your event subscriber in the module's services file... (see EventSubscriber Example for a full example.


      class: Drupal\response_test\404RedirectResponseSubscriber
        - { name: event_subscriber }

Then create a class to handle the event



namespace Drupal\response_test;

use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;

class 404RedirectResponseSubscriber implements EventSubscriberInterface {
  public function onRespond(FilterResponseEvent $event) {
    if ($event->getRequestType() !== HttpKernelInterface::MASTER_REQUEST) {
    $response = $event->getResponse();
    if ($response->getStatusCode() == 404) {

      // Get the old path somehow
      // @see https://stackoverflow.com/q/11047305
      $oldPath = ''; // Try using $response->getUri() or $response->headers->get('location')

      // Manipulate the $oldPath to remove the last part
      // @see https://stackoverflow.com/a/51573313/5771750
      $redirectPath = dirname($oldPath);

      $new_response = new RedirectResponse($redirectPath );

      // Prepare a new Symfony\Component\HttpFoundation\Response and use

  public static function getSubscribedEvents() {
    $events[KernelEvents::RESPONSE][] = array('onRespond');
    return $events;

Note: This answer is partly based of Clive's answer here: https://drupal.stackexchange.com/a/86622


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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