Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save paboden/137ea596a544e9c5025f3050566c8a3c to your computer and use it in GitHub Desktop.

Select an option

Save paboden/137ea596a544e9c5025f3050566c8a3c to your computer and use it in GitHub Desktop.
Drupal 8/9: Create a redirect response, using event subscribers, from old url to new url
# This code goes into module/src/EventSubscriber/MyModuleEventSubscriber.php file
<?php
namespace Drupal\MY_MODULE\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Redirect old url to new url.
*/
class MyModuleEventSubscriber implements EventSubscriberInterface {
/**
* Checks if current url needs to redirect.
*/
public function checkForOldUrlAndRedirect(RequestEvent $event) {
// This is needed for reasons.
if (!$event->isMasterRequest()) {
return;
}
$request = $event->getRequest();
$path = $request->getRequestUri();
$urls_to_redirect = [
'/old/url/path/file.pdf' => '/new/url/path/file.pdf'
'/old/url/path/page' => '/new/url/path/page'
'/old/url/path/image.png' => '/new/url/path/image.png'
]
// Check if our path starts with an "old" url.
foreach ($urls_to_redirect as $old => $new) {
// Check if our path starts with old url.
if (strpos($path, $old) !== FALSE) {
// Create a redirect response.
$redirect = new RedirectResponse($request->getBasePath() . $new, 302);
// Trigger the response redirect.
$event->setResponse($redirect);
}
}
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
return [KernelEvents::REQUEST => [['checkForOldUrlAndRedirect', 99]]];
}
}
# This code goes into module/mymodulename.services.yml file.
# It is needed in order to tell Drupal that you have an event subscriber that needs to be added to services.
# Otherwise, drupal will not see your subscriber.
services:
hdro_alter.my_module_redirect_event_subscriber:
class: Drupal\MYMODULENAME\EventSubscriber\MyModuleEventSubscriber
tags:
- { name: event_subscriber }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment