Drupal 8 How to change the default /user/login path

Profile picture for user a.berramou
Azz-eddine BERRAMOU 27 January, 2020

In some cases you allow only administrators to login to your Drupal site, so you don't want anyone to know the login path.
but if someone know that your website build with Drupal which is easy just by installing browser extension like Wappalyzer or just by simple inspect of one page source code then that someone know the login path is user/login, so the solution is to change the default 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 '/my-website/my-bo/login'.
        if ($route = $collection->get('user.login')) {
          $route->setPath('/my-website/my-bo/login');
        }
      }
    
    }
    

     

  3. Now we should register the below class as an event subscriber service, to do so:
    Create 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!