FOSHttpCacheBundle
repository·3.x·Indexed 19 days ago
https://github.com/friendsofsymfony/foshttpcachebundleA Symfony bundle providing advanced HTTP caching management. It enables sophisticated header configuration via path, host, or controller rules and supports active cache invalidation (purge, refresh, and tag-based) for proxies like Varnish, Nginx, and Symfony's built-in HttpCache. Key features include a Flash Message Listener to prevent session-based cache pollution and a CacheManager for manual or automatic invalidation.
What's inside FOSHttpCacheBundle
- FOSHttpCacheBundle is a Symfony bundle designed to improve HTTP caching performance. It provides tools to set global caching headers based on request attributes like path or controller, and integrates with the FOSHttpCache library to enable active invalidation of caching proxies (like Varnish).
Overview of FOSHttpCacheBundle functionality
3.xThe bundle provides several ways to manage cache behavior through attributes, configuration, or manual calls:
Functionality Attributes Configuration Manually Set Cache-Control headers Symfony cache attributes Symfony cache controlTag and invalidate #[Tag]rulescache managerInvalidate routes invalidatorscache managerInvalidate paths invalidatorscache managerMatch requests by host, controller, query string, or path
3.xWhen defining
rulesundercache_control, you can use thematchkey to target specific requests. Supported matching criteria include:- host: Match based on the request host using a regex (e.g.,
^login.example.com$). - attributes: Match based on request attributes, such as the controller (e.g.,
attributes: { _controller: ^AcmeBundle:Default:.* }). - query_string: Match based on the presence of specific parameters in the URL (e.g.,
query_string: (^|&)token=). - path: Match based on the URL path using a regex (e.g.,
path: ^/$).
fos_http_cache: cache_control: rules: # Match by host - match: host: ^login.example.com$ headers: cache_control: { public: false } # Match by controller - match: attributes: { _controller: ^AcmeBundle:Default:.* } headers: cache_control: { public: true } # Match by query parameter - match: query_string: (^|&)token= headers: cache_control: { public: false } # Match by path - match: path: ^/ headers: cache_control: { public: true }- host: Match based on the request host using a regex (e.g.,
How User Context works with caching proxies
3.xUser Context allows you to cache content that varies based on user groups (e.g., guest, editor, admin) without storing a separate cache for every individual user. It uses a 'preflight' request mechanism to determine a unique hash for the user's context.
The Workflow:
- A client requests a resource (e.g.,
/foo). - The proxy server (like Varnish) intercepts the request and sends a hash request to a specific context hash route.
- The application receives this hash request. The
UserContextListenerintercepts it after the Symfony firewall is applied, calculates a hash via aHashGenerator, and returns a response containing the hash in a custom header (default:X-User-Context-Hash). - The proxy server receives the hash, attaches it to the original client request for
/fooas a header, and restarts the request. - The application sees the header and, if configured, responds with
Vary: X-User-Context-Hash. The proxy then caches the response specifically for that hash.
This feature is compatible with Varnish and symfony-http-cache.
- A client requests a resource (e.g.,
Define which HTTP status codes are considered cacheable
3.xBy default, FOSHttpCacheBundle follows
RFC 7231, treating responses with the following status codes as cacheable:200, 203, 204, 206, 300, 301, 404, 405, 410, 414, or 501.
You can customize this behavior by configuring the
cacheable.responsesection in your bundle configuration.How to use match sections to limit configuration
3.xThe
matchsection is used withincache <headers>,invalidation <invalidation>, andtag rule <tags>configurations to restrict rules to specific requests and responses.A
matchsection contains one or more criteria, all of which are treated as regular expressions. For a rule to apply, the request must satisfy all provided criteria.Important Note on Encoding: Some parts of the URL are URL-encoded. However, the expressions provided in this configuration MUST NOT be URL-encoded. The matcher automatically handles encoding before performing the match.
match: host: ^login.example.com$ path: ^/$ query_string: (^|&)token=Use the Flash Message Listener to avoid session-based cache pollution
3.xBy default, Symfony flash messages are stored in the user session. When using features like
user contextto cache pages for logged-in users, including flash messages in the rendered HTML can cause notifications to be mixed up between different users or cached incorrectly.To solve this, the Flash Message Listener moves flash messages from the session into a cookie. The response is sent with a
SET-COOKIEheader, which ensures the response is not cached.Workflow:
- The server moves flash messages to a cookie.
- The client receives the cookie via a
SET-COOKIEheader. - Client-side JavaScript reads the cookie, renders the messages into the DOM, and then deletes the cookie.
Prerequisites: None.
Understand the criteria for a safe HTTP request
3.xIn the context of FOSHttpCacheBundle, a request is considered
safeif it uses one of the following HTTP methods:GETHEAD
How cache_control rules work
3.xThe
cache_controlconfiguration uses a list of rules to manage HTTP response headers. Each rule consists of amatchsection and aheaderssection.- Matching: When a request satisfies the parameters in the
matchsection, the correspondingheadersare applied to the response. - Execution Order: Rules are evaluated in the order they are defined. The first match wins.
- Header Overwriting: By default, headers are only set if they are not already present on the response. However, you can control this behavior using:
- A global
defaults.overwritesetting. - A per-rule
headers.overwrite: trueoption.
- A global
If
overwriteistrue, the headers defined in that rule will replace existing headers.fos_http_cache: cache_control: defaults: overwrite: false rules: - match: host: ^login.example.com$ headers: overwrite: true cache_control: public: false max_age: 0 s_maxage: 0- Matching: When a request satisfies the parameters in the
Compatibility with caching proxies
3.xWhile the bundle is fully functional with Varnish and used in production environments, other proxies have limited support:
- Varnish: Full support.
- Nginx: Partial support.
- Symfony built-in HttpCache: Partial support.
Use the CacheManager to invalidate or refresh content
3.xThe
FOS\HttpCacheBundle\CacheManageris used to explicitly invalidate or refresh content in your caching proxy.- Invalidating tells the proxy to stop serving a specific piece of content. The next time it is requested, the proxy fetches a fresh copy from the backend.
- Refreshing forces the proxy to fetch a fresh copy of the content immediately.
The
CacheManageris available in the Symfony DI container via autowiring.use FOS\HttpCacheBundle\CacheManager; // Injected via autowiring public function __construct(CacheManager $cacheManager) { ... }Key features of FOSHttpCacheBundle
3.xThe bundle provides several capabilities for managing HTTP cache:
- Path-based expiration: Configure cache expiration headers via application configuration based on the request path.
- Invalidation schemes: Set up cache invalidation without writing custom PHP code.
- Tag-based invalidation: Tag responses and invalidate specific cache entries using those tags.
- High-performance invalidation: Send invalidation requests to proxies with minimal performance impact.
- User-type differentiation: Differentiate cache versions based on user roles or types.
- Custom HTTP cache clients: Provides tools to easily implement your own HTTP cache client.