Reputation: 47784
I have read this http://madskristensen.net/post/add-expires-header-for-images and https://technet.microsoft.com/en-us/library/cc770661.aspx and other similar articles, who suggest to put this
<staticContent>
<clientCache httpExpires="Sun, 29 Mar 2020 00:00:00 GMT" cacheControlMode="UseExpires" />
</staticContent>
But even after that the images are not fetched from cache and 200 ok response is sent, that is a request to the server is made. I want no request to be made for x hours/days coz these image wont change for a long time.
How do I do this ?
Upvotes: 7
Views: 8737
Reputation: 303
The following configuration should cause browsers to cache your images for an entire year:
<staticContent>
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="365.00:00:00" />
</staticContent>
<httpProtocol>
<customHeaders>
<add name="Cache-Control" value="public" />
</customHeaders>
</httpProtocol>
You just need to make sure your images are being served as static file types. There is no way of forcing a browser to not send a request to the server ie; the user performs a hard fresh.
You can wrap the above configuration in a location node so as to only affect images that site in a certain path:
<location path="Content">
<system.webServer>
<staticContent>
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="365.00:00:00" />
</staticContent>
<httpProtocol>
<customHeaders>
<add name="Cache-Control" value="public" />
</customHeaders>
</httpProtocol>
</system.webServer>
</location>
The above configuration would add an HTTP cache header directive for all images hosted at http://www.example.com/Content/Images/*
You should create a configurable appsetting that is passed in to such images URI's as a query string parameter. This will allow you to clear all the clients to send a request the images from your server: (We want control over this as cached images can be problematic)
<img src="/Content/Images/MyImage.jpg?version=<%# Global.ImageVersion %>" />
More on caching headers (Cache-Control) here http://www.mobify.com/blog/beginners-guide-to-http-cache-headers/
I hope that helps!
Upvotes: 9