We know the Redirect module is an awesome way to create redirects for individual paths. But after a migration I needed to do some typical redirections. 

Example

mysite.com/news/* need to go to mysite.com/blog/*

Solution

We start with adding a services.yml file called mymodule.services.yml to our module:

services:
  mymodule.event_subscriber:
    class: Drupal\mymodule\EventSubscriber\CustomRedirects
    tags:
      - {name: event_subscriber}

Then we add a file to mymodule/src/EventSubscriber/CustomRedirects.php:

<?php

namespace Drupal\mymodule\EventSubscriber;

use Drupal\Core\Url;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Class CustomRedirects
 * @package Drupal\mymodule\EventSubscriber
 *
 * Redirects /news/* to '/blog/*'
 */
class CustomRedirects implements EventSubscriberInterface {

  public function checkForRedirection(RequestEvent $event) {

    $request = $event->getRequest();
    $path = $request->getRequestUri();
    if(strpos($path, 'news/') !== false) {
      // Redirect old  urls
      $new_url = str_replace('news/','blog/', $path);
      $new_response = new RedirectResponse($new_url, '301');
      $new_response->send();
    }

    // This is necessary because this also gets called on
    // node sub-tabs such as "edit", "revisions", etc.  This
    // prevents those pages from redirected.
    if ($request->attributes->get('_route') !== 'entity.node.canonical') {
      return;
    }

  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    //The dynamic cache subscribes an event with priority 27. If you want that your code runs before that you have to use a priority >27:
    $events[KernelEvents::REQUEST][] = array('checkForRedirection', 29);
    return $events;
  }

}

 

 

 

Saved you some valuable time?

Received 100 so far from 4 kind contributors.