Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting and preventing cache in Symfony2

Tags:

symfony

I am doing this:

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

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

domain.com/route-name/

It allows an action to take place regardless of the page viewing (cookie stores a setting for the user).

I am using the default Symfony2 reverse-proxy cache and all is well, but I need to prevent both the above requests from caching.

I am using this to perform the redirect:

// $event being a listener, usually a request listener

$response = new RedirectResponse($url, 302);    
$this->event->setResponse($response);

I've tried things like this but nothing seems to work:

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

So how do I stop it caching those pages?

like image 919
user2143356 Avatar asked May 25 '13 19:05

user2143356


1 Answers

You have to make sure you are sending the following headers with the RedirectResponse ( if the GET parameter is set ) AND with your regular Response for the route:

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

Achieve what you want like this:

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

private is important and missing in coma's answer.

The difference is that with Cache-Control: private you are not allowing proxies to cache the data that travels through them.

like image 85
Nicolai Fröhlich Avatar answered Oct 11 '22 08:10

Nicolai Fröhlich