Tripped up on how to make my EventSubscriber code run on every page load. In my src/EventSubscriber/RedirectAnonymousSubscriber.php file here's my code:


namespace Drupal\mymodule\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

 * Event subscriber subscribing to KernelEvents::REQUEST.
class RedirectAnonymousSubscriber implements EventSubscriberInterface {
  private $redirectCode = 301;

  public function checkForRedirection(GetResponseEvent $event) {
    $is_authenticated = \Drupal::currentUser()->isAuthenticated();
    $route_name = \Drupal::routeMatch()->getRouteName();

    if (!$is_authenticated && $route_name !== 'user.login') {
      $response = new RedirectResponse('https://example.com', $this->redirectCode);

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

And then my .services.yml file:

    class: Drupal\mymodule\EventSubscriber\RedirectAnonymousSubscriber
      - { name: event_subscriber }

The weird thing is when I run drush cr and pull up my local env, the first time I log in the redirection works, however, anytime I log in after the first time running drush cr the redirection does not work correctly. I even put a breakpoint on my if statement in my function and it doesn't get hit after the first successful redirection. Hope that makes sense. Thanks!