HTTP Caching

HTML pages referred static files (images, js and css etc) can be cached in your browser by setting HTTP response header attributes about cache.

Two main types of cache headers, cache-control and expires, define the caching characteristics for your resources. Typically, cache-control is considered a more modern and flexible approach than expires, but both headers can be used simultaneously.

Cache headers are applied to resources at the server level – for example, in the .htaccess file on an Apache server, used by nearly half of all active websites – to set their caching characteristics. Caching is enabled by identifying a resource or type of resource, such as images or CSS files, and then specifying headers for the resource(s) with the desired caching options.

Stop using (HTTP 1.0) Replaced with (HTTP 1.1 since 1999)
Expires: [date] Cache-Control: max-age=[seconds]
Pragma: no-cache Cache-Control: no-cache

Setting HTTP cache in Spring framework

Setting HTTP response cache-control header in Spring framework

return ResponseEntity.ok()
.cacheControl(CacheControl.maxAge(365, TimeUnit.DAYS)
.cachePrivate()
.mustRevalidate())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + fileName + "\"")
.body(resource);

Setting HTTP cache in Nginx Server

Only set HTTP Cache-Control header for HTTP directly response by Nginx, not proxy_pass server HTTP responses. In other words, request static files via the server’s file path. For example:

  • expires 30d;
  • add_header Cache-Control “public, no-transform”;

conf/nginx.conf

server {
listen 80;
server_name localhost;
location / {
autoindex on;
root html;
index index.html index.htm;
}
location ~* \.(js|css|png|jpg|jpeg|gif|svg|ico)$ {
root /root/upload
expires 30d;
add_header Cache-Control "public, no-transform";
}
}

Cache-Control Directives

Cache

  • Cache types: private / public
  • Expired time: max-age / s-maxage
  • validated-related: no-cache, must-revalidate/proxy-revalidate, stale-while-revalidate, stale-if-error
  • no-transform
  • immutable

Examples:

Cache-Control: public, max-age=604800, must-revalidate

No Cache

  • no-store or max-age=0

Note that no-cache does not mean “don’t cache”. no-cache allows caches to store a response but requires them to revalidate it before reuse. If the sense of “don’t cache” that you want is actually “don’t store”, then no-store is the directive to use.

Examples

Cache-Control: no-store

Cache-Control Directive Details

Max Age for Files

  • ico/jpg/jpeg/png/gif: max-age=2592000 seconds (30 days) or max-age=31536000 (365 days)
  • pdf: max-age=2592000 seconds (30 days)
  • css/js: max-age=86400 seconds (1 hours) or max-age=2592000 seconds (30 days)

References