5

I've implemented a conditional redirect on my site via an event subscriber and returning a redirect response. It's working but, I believe due to the page_cache module is getting cached for anonymous users.

This is basically what I'm using to set the redirect response:

public function checkRedirectStatus(GetResponseEvent $event) {
    if(shouldIRedirect()) {
        $response = new RedirectResponse('/redirect/path');
        $event->setResponse($response);
     }
}

The above gets cached whether or not it returns true unless I add \Drupal::service('page_cache_kill_switch')->trigger();.

As this is a fairly high-traffic page I'm concerned about bypassing cache for anonymous users. Are there other options I'm not aware of?

If this is on the REQUEST kernel event, how far-reaching is page_cache_kill_switch?

Thanks for your help!

2
  • 2
    How far-reaching is page_cache_kill_switch? This depends on how often you trigger it. You need it for all pages where theoretically the redirect could happen. If this is the entire site, then all your content is dynamic and the internal page cache doesn't make any sense and you can un-install it. In this case use a cacheable redirect response, see the answer of @sonfd, so that you can take full advantage of the dynamic page cache.
    – 4uk4
    Commented Apr 4, 2019 at 15:55
  • What sort of logic are you using for your redirect? Could you use an InboundPathProcessor instead of an EventSubscriber?
    – Darvanen
    Commented Apr 9, 2019 at 23:15

1 Answer 1

12

This doesn't exactly answer your question, but I feel it's relevant information. I did something similar, but I also didn't like using the kill switch. In another iteration I used a TrustedRedirectResponse which allowed me to handle my cache issue differently. My understanding is this is forcing browsers to always bypass cache when executing the redirect, but the redirect itself is cached by Drupal until $entity's (my cache dependency) cache is invalidated.

$response_headers = [
  'Cache-Control' => 'no-cache, no-store, must-revalidate',
];

$response = new TrustedRedirectResponse($url, '302', $response_headers);
// In my case $entity is a content entity where my redirect $url is generated.
// In your case you'd add cache dependencies relevant to determining shouldIRedirect().
$response->addCacheableDependency($entity);
$event->setResponse($response);
1
  • in my case, the relevant cache dependency is the current user's role. But when I add the current user object via addCacheableDependency(), the response is still cached for anonymous. How do I tell Drupal to serve the cached response based on the current user? Commented May 9, 2023 at 15:51

Your Answer

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

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