Created
May 27, 2022 20:34
-
-
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 file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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 file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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