HTTP Cache ExpirationEdit this page
Warning: You are browsing the documentation for Symfony 6.1, which is no longer maintained.
Read the updated version of this page for Symfony 6.3 (the current stable version).
HTTP Cache Expiration
The expiration model is the most efficient and straightforward of the two caching models and should be used whenever possible. When a response is cached with an expiration, the cache returns it directly without hitting the application until the cached response expires.
The expiration model can be accomplished using one of two, nearly identical,
Expiration and Validation
You can use both validation and expiration within the same
As expiration wins over validation, you can benefit from the best of
both worlds. In other words, by using both expiration and validation, you
can instruct the cache to serve the cached content, while checking back
at some interval (the expiration) to verify that the content is still valid.
You can also define HTTP caching headers for expiration and validation by using annotations. See the FrameworkExtraBundle documentation.
Expiration with the
Most of the time, you will use the
Cache-Control header, which
is used to specify many different cache directives:
1 2 3 4
// sets the number of seconds after which the response // should no longer be considered fresh by shared caches $response->setPublic(); $response->setMaxAge(600);
Cache-Control header would take on the following format (it may have
Cache-Control: public, max-age=600
setSharedMaxAge() method is not equivalent to using both
setMaxAge() methods. According to the
Serving Stale Responses section of RFC 7234, the
setSharedMaxAge() method) prohibits a cache to use a stale
stale-if-error scenarios. That's why it's recommended to use
Expiration with the
An alternative to the
Cache-Control header is
Expires. There's no advantage
or disadvantage to either.
According to the HTTP specification, "the
Expires header field gives
the date/time after which the response is considered stale." The
header can be set with the
Response method. It takes a
DateTime instance as an argument:
1 2 3 4
$date = new DateTime(); $date->modify('+600 seconds'); $response->setExpires($date);
The resulting HTTP header will look like this:
Expires: Thu, 01 Mar 2011 16:00:00 GMT
setExpires() method automatically converts the date to the GMT
timezone as required by the specification.
Note that in HTTP versions before 1.1 the origin server wasn't required to
Date header. Consequently, the cache (e.g. the browser) might
need to rely on the local clock to evaluate the
Expires header making
the lifetime calculation vulnerable to clock skew. Another limitation
Expires header is that the specification states that "HTTP/1.1
servers should not send
Expires dates more than one year in the future."
According to the Calculating Freshness Lifetime section of RFC 7234,
Expires header value is ignored when the
directive of the
Cache-Control header is defined.