3

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
    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. – 4k4 Apr 4 '19 at 15:55
  • What sort of logic are you using for your redirect? Could you use an InboundPathProcessor instead of an EventSubscriber? – Darvanen Apr 9 '19 at 23:15
5

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. This worked well for me. My understanding is this is forcing browsers to always bypass cache when executing the redirect, but the Redirect itself is cached in 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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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