Symfony 3.4版本HTTP缓存失效问题求助
Let's break down why your reverse proxy cache isn't behaving as expected in Symfony 3.4.8, and walk through targeted fixes:
Common Causes & Solutions
1. Debug Mode Blocks Cache by Default
Symfony's AppCache (the reverse proxy implementation) automatically disables caching when the kernel runs in debug mode—which your app_dev.php enables with new AppKernel('dev', true). This stricter behavior is a key change from Symfony 3.2, where debug mode didn't override the proxy's cache logic as aggressively.
Fix: Force-disable debug mode specifically for the reverse proxy in app_dev.php:
$kernel = new AppKernel('dev', true); if (PHP_VERSION_ID < 70000) { $kernel->loadClassCache(); } // Override debug setting to enable caching for the reverse proxy $kernel = new AppCache($kernel, [ 'debug' => false, ]);
2. Debug Toolbar Overrides Your Cache Headers
The Symfony Debug Toolbar (enabled by default in dev environments) injects a Cache-Control: no-cache header into every response, which directly overrides your setSharedMaxAge(3600) call.
Fix: Explicitly set cache headers and remove debug toolbar markers in your controller:
public function indexAction(Request $request) { // [...] $response = $this->render('base.html.twig'); // Set explicit cache headers to override toolbar interference $response->headers->set('Cache-Control', 'public, s-maxage=3600, max-age=3600'); // Remove debug toolbar headers to prevent cache bypass if ($this->get('kernel')->isDebug()) { $response->headers->remove('X-Debug-Token'); $response->headers->remove('X-Debug-Token-Link'); } return $response; }
3. AppCache Default Options Changed in 3.4
Symfony 3.4 updated default HttpCache options that can block caching. For example, allow_reload now defaults to true, which lets browsers bypass the proxy cache with Cache-Control: no-cache requests.
Fix: Update your AppCache class to enforce cache-friendly settings:
// app/AppCache.php class AppCache extends HttpCache { protected function getOptions() { $baseOptions = parent::getOptions(); // Override options to enforce consistent caching $customOptions = [ 'debug' => false, 'allow_reload' => false, // Prevent browser-initiated cache bypass 'allow_revalidate' => false, 'default_ttl' => 3600, // Fallback TTL if no header is set ]; return array_merge($baseOptions, $customOptions); } }
Verify the Fix
After applying these changes, confirm caching works by:
- Checking response headers for
Cache-Control: public, s-maxage=3600, max-age=3600 - Confirming your controller action only runs once per hour (instead of on every request)
内容的提问来源于stack exchange,提问作者Piotrek Zatorski

