February 5, 2015
Each response your server delivers for an asset should specify an explicit caching policy that answers the following questions:
- Can the resource be cached?
- By whom can it be cached?
- How long can it be cached?
- How can it be revalidated when caching policy expires?
When your server returns a response, it must provide the Cache-Control header. This header defines how, and for how long, the individual response can be cached by the browser and other intermediate caches.
The recommended minimum cache time is one week, or up to one year for static assets or other assets that change infrequently.
How to Add Cache-Control Headers
The headers can be added on your origin server or in your MaxCDN control panel.
If added on the origin server, your CDN will replicate them and pass them through regularly. The cache-control header on the origin will also affect the MaxCDN cache and determine how long the file be cached on it.
How to Add Headers in MaxCDN CP
- Navigate to Settings page. Here you can change the configuration of your zone.
- Before proceeding with adding the header, ignore the cache control header sent by origin (Under zone Edge Settings) so you can dictate TTL (Default Cache Time) on CDN as well as browser cache time with Override Cache Control Header.
After ignoring the Cache Control headers, the Override value can be applied in the Cache Settings section.
- After applying the necessary changes, the MaxCDN cache should be purged in order for new headers to be applied. The MaxCDN cache can be purged from the Manage Cache page that’s available in the zone sub navigation. More details regarding the purging of the MaxCDN cache can be found in this tutorial.
Changing Your .htaccess File
To add the header on your origin server, you should change the .htaccess by changing the max-age value to the desired interval.
# 1 YEAR <FilesMatch "\.(flv|ico|pdf|avi|mov|ppt|doc|mp3|wmv|wav)$"> Header set Cache-Control "max-age=31536000, public" </FilesMatch> # 1 WEEK <FilesMatch "\.(jpg|jpeg|png|gif|swf)$"> Header set Cache-Control "max-age=604800, public" </FilesMatch> # 3 HOUR <FilesMatch "\.(txt|xml|js|css)$"> Header set Cache-Control "max-age=10800" </FilesMatch> # NEVER CACHE - notice the extra directives <FilesMatch "\.(html|htm|php|cgi|pl)$"> Header set Cache-Control "max-age=0, private, no-store, no-cache, must-revalidate" </FilesMatch>
Testing The Headers
You can verify if the Cache-Control: max-age header is in place on your files by running a “curl” command like:
curl -I http://foo.bar.netdna-cdn.com/file.ext HTTP/1.1 200 OK Date: Fri, 16 Sep 2014 14:12:20 GMT Content-Type: text/css Connection: keep-alive Cache-Control: max-age=604800, public ← 1 Week caching time Expires: Thu, 21 May 2015 20:00:00 GMT Vary: Accept-Encoding Last-Modified: Thu, 24 Jan 2013 20:00:00 GMT GMT; path=/; domain=.domain.com Server: NetDNA-cache/2.2 X-Cache: HIT