3

My question is the same asked in How do I redirect from /index.php/event/* to /event? but for Drupal 8.

Since the module suggested in the accepted answer for that question doesn't have a version for Drupal 8, how can I achieve the same with Drupal 8?

3 Answers 3

2

In Drupal 8 you use an event subscriber for this. You subscribe to a REQUEST kernel event, get the original url from the request, apply a regular expression and if this finds a replacement set the new url as a 301 redirect response.

mymodule/src/EventSubscriber/RedirectSubscriber.php

<?php

namespace Drupal\mymodule\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Drupal\Core\Routing\TrustedRedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;

class RedirectSubscriber implements EventSubscriberInterface {

  public function redirectIndexPHP(GetResponseEvent $event) {
    $old_url = $event->getRequest()->getUri();
    $new_url = preg_replace('|/index.php|', '', $old_url, 1, $count);
    if ($count > 0) {
      $response = new TrustedRedirectResponse($new_url, 301);
      $event->setResponse($response);
    }
  }

  static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('redirectIndexPHP', 39);
    return $events;
  }

}

mymodule/mymodule.services.yml

services:
  mymodule.redirect:
    class: Drupal\mymodule\EventSubscriber\RedirectSubscriber
    arguments: []
    tags:
      - { name: event_subscriber }
0

I believe you can do it as follows (untested):

use \Symfony\Component\HttpFoundation;

function somePageCallback()
{
   ...

   return new RedirectResponse('/path/to/redirect/to');
}
0

Here is the Rewrite Rule to be written in .htaccess file located in Drupal Root directory.

RewriteEngine on
RewriteCond %{REQUEST_URI} index.php/event/
RewriteRule ^(.*) http://www.domain.com/event [L,R=301]

Hope, it makes sense to you.

1
  • 1
    .htaccess files usually pushed up with core changes and are prone to getting overwritten. Commented Nov 8, 2018 at 19:19

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.