How to configure static content cache per folder and extension in IIS7?

frankadelic picture frankadelic · Feb 3, 2010 · Viewed 116.2k times · Source

I would like to set up rules in IIS7 for static content caching in my ASP.NET website.

I have seen these articles, which details how to do it using the <clientCache /> element in web.config:

Client Cache <clientCache> (IIS.NET)
Add Expires or Cache Control Header to static content in IIS (Stack Overflow)

However, this setting appears to apply globally to all static content. Is there a way to do this just for certain directories or extensions?

For example, I may have two directories which need separate cache settings:

/static/images
/content/pdfs

Is it possible to set up rules for sending cache headers (max-age, expires, etc) based on extensions and folder paths?

Please note, I must be able to do this via web.config because I don't have access to the IIS console.

Answer

Kev picture Kev · Feb 4, 2010

You can set specific cache-headers for a whole folder in either your root web.config:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <!-- Note the use of the 'location' tag to specify which 
       folder this applies to-->
  <location path="images">
    <system.webServer>
      <staticContent>
        <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="00:00:15" />
      </staticContent>
    </system.webServer>
  </location>
</configuration>

Or you can specify these in a web.config file in the content folder:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <staticContent>
      <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="00:00:15" />
    </staticContent>
  </system.webServer>
</configuration>

I'm not aware of a built in mechanism to target specific file types.