Enable browser caching for static resources

2019-08-08 15:08发布

问题:

To improve the site performance, I'm adding following http headers in IIS 7.5.

Expires: Sun, 29 Mar 2020 00:00:00 GMT and Cache-Control:Public

I'm adding these headers for images folder in site's virtual directory. When I access the site, I see that for each image present in this folder; those response headers were:

Accept-Ranges:bytes Cache-Control:no-cache, no-store,Public Content-Length:4445 Content-Type:image/png Date:Fri, 06 Jun 2014 09:18:36 GMT ETag:"16874c2af55ecf1:0" Expires:-1,Sun, 29 Mar 2020 00:00:00 GMT Last-Modified:Wed, 23 Apr 2014 13:08:48 GMT max-age:604800 Pragma:no-cache Server:Microsoft-IIS/7.5 X-Powered-By:ASP.NET

I need browser to take these images from it's cache instead of requesting again from server. How should I achieve it?

回答1:

Your header shows that you add a new value but you need to replace the existing one

Cache-Control:no-cache, no-store,Public
Expires:-1,Sun, 29 Mar 2020 00:00:00 GMT

no-cache, no-store stands for no cache and -1 says that the content is already expired.

Instead of doing it from the code you can easily set it in the root web.config file as

...
  <location path="images">
    <system.webServer>
      <staticContent>
        <clientCache cacheControlMode="UseExpires" 
                     httpExpires="Sun, 29 Mar 2020 00:00:00 GMT" /> 
      </staticContent>
    </system.webServer>
  </location>
</configuration>

where images is a name of your directory

or add dedicated web.config file directly in the target directory

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <staticContent>
      <clientCache cacheControlMode="UseExpires" 
                   httpExpires="Sun, 29 Mar 2020 00:00:00 GMT" /> 
    </staticContent>
  </system.webServer>
</configuration>

You can also use cacheControlMode="UseMaxAge" and set specific time of expiration

Example to set expiration in 7 days

<clientCache cacheControlMode="UseMaxAge" 
             cacheControlMaxAge="7.00:00:00" /> 

Read more http://msdn.microsoft.com/en-us/library/ms689443.aspx