Redirecting and preventing caching in Symfony2

I'm doing it:

domain.com/route-name/?do-something=1 

.. which sets a cookie and then redirects it using a 302 redirect:

 domain.com/route-name/ 

It allows you to perform an action regardless of page view (cookie saves settings for the user).

I use Symfony2 reverse proxy by default, and everything is fine, but I need to prevent both of these requests from being cached.

I use this to do the redirection:

 // $event being a listener, usually a request listener $response = new RedirectResponse($url, 302); $this->event->setResponse($response); 

I tried things like this, but nothing works:

 $response->setCache(array('max_age' => 0)); header("Cache-Control: no-cache"); 

So how do I stop caching these pages?

+4
source share
2 answers

You need to make sure that you send the following headers using RedirectResponse (if the GET parameter is set) and with your regular answer for the route:

 Cache-Control: private, max-age=0, must-revalidate, no-store; 

Reach what you want:

 $response->setPrivate(); $response->setMaxAge(0); $response->setSharedMaxAge(0); $response->headers->addCacheControlDirective('must-revalidate', true); $response->headers->addCacheControlDirective('no-store', true); 

personal is important and missing from the coma report.

The difference is that with Cache-Control: private you do not allow proxies to cache the data that passes through them.

+8
source

Try this in response:

 $response->headers->addCacheControlDirective('no-cache', true); $response->headers->addCacheControlDirective('max-age', 0); $response->headers->addCacheControlDirective('must-revalidate', true); $response->headers->addCacheControlDirective('no-store', true); 

You can also use annotations:

http://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/cache.html

And take a look at:

Why should the HTTP response use both a cache and a no-store?

+1
source

Source: https://habr.com/ru/post/1482751/


All Articles