I am trying to redirect unauthenticated users. So anytime an unauthenticated user tries to get to the base url, redirect them to an external url. Currently works, but continues to redirect to the external url even after user is authenticated and logged in. So I am trying to disable cache whenever the base URL is accessed.

Here is my current code for redirecting in my src/EventSubscriber/RedirectAnonymousSubscriber.php file:

class RedirectAnonymousSubscriber implements EventSubscriberInterface {
  private $redirectCode = 301;

  public function checkForRedirection(GetResponseEvent $event) {
//    to kill page caching:
//    \Drupal::service('page_cache_kill_switch')->trigger();
    $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', 30);
    return $events;

Would that would be the correct way to go about things? And how would I go about implementing that in my *.routing.yml file and elsewhere? Thanks!

1 Answer 1


Not Drupal specific, but you should use the status code 302. Redirects with a status code 301 are cached very aggressively by browsers.

In Drupal custom code, never send a response directly, set it in the event, so that it can be returned and cached properly by Drupal, which is by the way not a bad thing, because the page cache can handle different cached versions for authenticated and anonymous users:

  • thank you I'll try that! So I replace $response->send(); exit(0); with $event->setResponse($response);? Or do I leave the exit(0); there? Feb 4, 2020 at 20:30
  • No exit either, just set the response. The event dispatcher will find this response and then exit the kernel in the correct way. Found this great answer how you can set headers to control specifically the browser cache, if you need to: drupal.stackexchange.com/a/278703/47547
    – 4uk4
    Feb 4, 2020 at 20:37
  • thank you! Looks promising:) Feb 4, 2020 at 20:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.