How to redirect user page to front page for specific roles I want to redirect every users page to front page? like if user page url is /user/97 then it redirect to front page if user is not administrator. I want user page inaccessible to other users but only administrators.

How can I achieve this?

I tried doing like this:

&lt;?php

namespace Drupal\myisu_ubit\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;
// use Drupal\user\Entity\User;

 /**
   * Listens to the dynamic route events.
   */
 class RouteSubscriber extends RouteSubscriberBase {

 /**
  * {@inheritdoc}
  */
 protected function alterRoutes(RouteCollection $collection) {
   // Change the route associated with the user profile page (/user, /user/{uid}).
   if ($route = $collection-&gt;get('user.page')) {
      $route-&gt;setPath('/');
   } 
 }

}


module.services.yml:

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


What am I doing wrong here?
Solved using EventSubscriber like this:

services:
  my_module.event_subscriber:
    class: Drupal\my_module\EventSubscriber\MyModuleSubscriber
    tags:
       - {name: event_subscriber}


And MyModuleSubscriber:

namespace Drupal\my_module\EventSubscriber;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\views\Views;
use Drupal\views\ViewExecutable;
use Drupal\user\Entity\User;
use Drupal\Core\Url;

class MyModuleSubscriber implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public function checkForRedirection(GetResponseEvent $event) {
    $request = \Drupal::request();
    $requestUrl = $request-&gt;server-&gt;get('REQUEST_URI', NULL);
    $userID = \Drupal::currentUser()-&gt;id();
    $user = User::load($userID);
    $uid = $user-&gt;get('uid')-&gt;value;
    $roles = $user-&gt;getRoles();
    $userPage = "/user/" . $userID;
    if (
      $userID !== '1' &amp;&amp; 
      !in_array('administrator', $roles) &amp;&amp;
      $requestUrl == $userPage
    ) {
        $path =  \Drupal::service('path.alias_manager')-&gt;getAliasByPath('/');
      $event-&gt;setResponse(new RedirectResponse($path, 301));
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('checkForRedirection');
    return $events;
  }

}


I don't know if it is the correct way to do this but it solves my problem.