Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh

How to redirect anonymous user in Drupal 8 & 9


Create file

name: Redirect Anonymous User
type: module
description: Redirect anonymous user to login page
package: Custom
core: 8.x


Create custom service like this:

    class: Drupal\redirect_anonymous_user\EventSubscriber\RedirectAnonymousUser
    arguments: []
      - {name: event_subscriber}


Create class RedirectAnonymousUser:


namespace Drupal\redirect_anonymous_user\EventSubscriber;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\Core\Url;

 * Event subscriber subscribing to KernelEvents::REQUEST.
class RedirectAnonymousUser implements EventSubscriberInterface

    public function __construct() {
        $this->account = \Drupal::currentUser();

    public function checkAuthStatus(GetResponseEvent $event) {

        if ($this->account->isAnonymous() && \Drupal::service('path.current')->getPath() == '/node/add/article') {

            // add logic to check other routes you want available to anonymous users,
            // otherwise, redirect to login page.
            $route_name = \Drupal::routeMatch()->getRouteName();
            if (strpos($route_name, 'view') === 0 && strpos($route_name, 'rest_') !== FALSE) {

            $response = new RedirectResponse('/user/login?destination=/node/add/article', 301);

    public static function getSubscribedEvents() {
        $events[KernelEvents::REQUEST][] = array('checkAuthStatus');
        return $events;


Add new comment

Restricted HTML


Page Facebook

Become a patron

If you need some help or you search a Drupal freelancer don't hesitate to contact us.


Contact Us

All the content is FREE but I still need your help


Become a patreon