Drupal 9 How To change the Default Routing Path

By toswebdev, 9 January, 2022
Drupal 9 How To change the Default Routing Path

Here we are going to alter or change the default login (user/login) path.

  1. First, create a custom module if you don't know how refer to creating custom module documentations page.
     
  2. Create a RouteSubscriber inside your module create Routing folder inside src folder and inside it create RouteSubscriber class RouteSubscriber.php like the followingRouteSubscriber folder structure


    and put in it the following code:

    <?php
    
    namespace Drupal\YOUR_MODULE_NAME\Routing;
    
    use Drupal\Core\Routing\RouteSubscriberBase;
    use Symfony\Component\Routing\RouteCollection;
    
    /**
     * Listens to the dynamic route events.
     */
    class RouteSubscriber extends RouteSubscriberBase {
    
      /**
       * {@inheritdoc}
       */
      protected function alterRoutes(RouteCollection $collection) {
        // Change path '/user/login' to '/secrete/login'.
        if ($route = $collection->get('user.login')) {
          $route->setPath('/secrete/login');
        }
      }
    
    }
    

     

  3. Now we should register the below class as an event subscriber service, to do so:
    Create a file in your root module folder called YOUR_MODULE_NAME.services.yml and put in it:
     

    services:
      YOUR_MODULE_NAME.route_subscriber:
        class: Drupal\YOUR_MODULE_NAME\Routing\RouteSubscriber
        tags:
          - { name: event_subscriber }
    

     

  4. Now just clear the cache and you are done!

Comments

All comments go through moderation, so your comment won't display immediately.