Thursday, October 21, 2010

IIS7: How to set cache control for static content?

Caching is popular technique for reducing network traffic and server recourses when it comes to web content. But how we can cache static content like .jpg, gif, .js files?! 
1. Allow overriding static content setting:
open %systemroot%\System32\inetsrv\config\applicationHost.config
search for

change it to
overrideModeDefault="Allow" />

 
2. set cache settings using following commands (from IIS.NET forums)
set max-age to 1hr for all static files under /images on default-web-site, run the following
 
\Windows\system32\inetsrv\appcmd.exe set config "Default Web Site/images" -section:system.webServer/staticContent -clientCache.cacheControlMode:UseMaxAge
 
\Windows\system32\inetsrv\appcmd.exe set config "Default Web Site/images" -section:system.webServer/staticContent -clientCache.cacheControlMaxAge:"01:00:00"
 
If you give it a shot now you will see that the content is cached! Not believe?! Try to request image from the browser, overwrite the image with image with same name and different content and request image from the browser again...
But the bad news is that caching is on the server - so you haven't reduced network traffic as web server is still hit.
 
3. Cache it on client
open %systemroot%\System32\inetsrv\config\applicationHost.config
and change the lines like this
 
<location path="MyWebsite"> 
<system.webServer> 
<caching> 
<profiles> 
<add extension=".html" policy="CacheUntilChange" kernelCachePolicy="DontCache" location="Client" /> 
<add extension=".htm" policy="CacheUntilChange" kernelCachePolicy="DontCache" location="Client" /> 
<add extension=".gif" policy="CacheUntilChange" kernelCachePolicy="DontCache" location="Client" /> 
<add extension=".js" policy="CacheUntilChange" kernelCachePolicy="DontCache" location="Client" /> 
<add extension=".css" policy="CacheUntilChange" kernelCachePolicy="DontCache" location="Client" /> 
<add extension=".jpg" policy="CacheUntilChange" kernelCachePolicy="DontCache" location="Client" /> 
<add extension=".jpeg" policy="CacheUntilChange" kernelCachePolicy="DontCache" location="Client" /> 
<add extension=".zip" policy="CacheUntilChange" kernelCachePolicy="DontCache" location="Client" /> 
<add extension=".rar" policy="CacheUntilChange" kernelCachePolicy="DontCache" location="Client" /> 
profiles> 
caching> 
system.webServer> 
location>
 
source: http://www.galcho.com/Blog/PermaLink.aspx?guid=490f3c31-1815-40fc-a871-5d6899fa35e0  

No comments: