It’s not uncommon needing to disable browser caching of some specific files or entire folders on your website or in your web application. Sometimes you need the user’s browser to not cache some specific files and always try to retrieve them from the server. I recently needed to do this while working with the HTML5 application cache to ensure that the browser updated all files listed in the manifest file when the manifest was updated.
There are two simle ways to achieve this.
Solution 1: Add a separate Web.config for each folder
If you want to disable caching of all files in a folder and its subfolders you can add a Web.config
in the root folder you want to disable browser caching for. Say you wanted to disable browser caching for the files in the folder js/nocache
and all subfolders, then you would place the Web.config here: js/nocache/Web.config
.
Add the following to the Web.config
to disable browser caching.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<staticContent>
<clientCache cacheControlMode="DisableCache" />
</staticContent>
</system.webServer>
</configuration>
The content of the Web.config
file is inherited for all subfolders.
Solution 2: Add the settings to the default Web.config
Another way is to add the settings directly to the default Web.config
of your project. This also enables you to control the browser caching for single files.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- Specific file -->
<location path="manifest.appcache">
<system.webServer>
<staticContent>
<clientCache cacheControlMode="DisableCache" />
</staticContent>
</system.webServer>
</location>
<!-- Folder including subfolders -->
<location path="js/nocache">
<system.webServer>
<staticContent>
<clientCache cacheControlMode="DisableCache" />
</staticContent>
</system.webServer>
</location>
</configuration>
The second part of this solution has the exact same results as the first solution.
Conclusion
By setting the <clientCache cacheControlMode="DisableCache" />
the server will add a few headers to the HTTP response instructing the browser to not cache the responses.
Here’s an example of an HTTP response after our changes:
HTTP/1.1 200 OK
Cache-Control: no-cache
Last-Modified: Wed, 01 Oct 2014 14:18:11 GMT
ETag: "b198e28782ddcf1:0"
Content-Type: text/css
Accept-Ranges: bytes
Date: Wed, 01 Oct 2014 14:25:43 GMT
Content-Length: 26685
The three headers, Cache-Control
, Last-Modified
and ETag
, have now been added and tells the browser to not cache the response.