Tuesday, April 19, 2011

Leverage browser caching by dummy configuration on Apache HTTP Server

Leverage browser caching is quite critical for web performance, especially you have , but sometime you may have your static files get changed. So you may control the risks as much as possible.

There is a cool strategy to Use fingerprinting to dynamically enable caching if you can, but if you just want to do some simple configurations with limited risks, then here is my sample httpd.conf:

 
 LoadModule headers_module modules/mod_headers.so
 ... 
 #Disable Last-Modified Response Header  
 <FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf|html|rpc)$">  
 Header unset Last-Modified  
 </FilesMatch>

 #Default Cache-control header for most static files  
 <FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">  
 Header set Cache-Control "max-age=7200, public"  
 </FilesMatch>  
 # Revalidate For No-cache files each time  
 <FilesMatch "\.nocache\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">  
 Header set Cache-Control "max-age=0, no-cache, must-revalidate"  
 </FilesMatch>  
 # Revalidate html/rpc files each time  
 <FilesMatch "\.(html|rpc)$">  
 Header set Cache-Control "max-age=0, no-cache, must-revalidate"  
 </FilesMatch>  
 # Cache "forever" due to files are given a unique name every time they are built  
 <FilesMatch "\.cache\.(html|js|png|gif)$">  
 Header set Cache-Control "max-age=2592000, public"  
 </FilesMatch>  

Let’s assume one yourapp.js has been requested for the first time and load into Disk cache:

1. when the browser requests yourapp.js within 2 hours(7200 seconds) since loaded into Disk cache, it will be load from Disk cache directly without sending any http request;

2. when the browser requests yourapp.js after 2 hours(7200 seconds) since loaded into Disk cache, it will be fetched either from static file server (200 code returned) if Etag has been changed(which means static file changes) or from Disk Cache (304 code returned) if Etag is still the same as request head brings ("if-none-match" request header) (which means static file has no changes)

3. Some no Cached files will always re-validate to the server, to check if the the file is the latest or not based on Etag

4. Some Cached files will have far further cache-control header (set to 1 month from my side), Due to every new build, the static file name will be refreshed, and we do monthly release usually.

No comments:

Post a Comment