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!

有帮助吗?

解决方案

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);
许可以下: CC-BY-SA归因
scroll top