File cache with .htaccess

时间:2016-04-04 16:39:17

标签: php apache .htaccess caching

A few months ago I looked around for some information regarding the best way to cache files (stylesheets, images) in our site. What I found was to add a few lines of code in the .htaccess file:

# Expires caching (Caching static files for longer drastically improves performance, you might even want to put even more aggressive times)
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType text/html "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresDefault "access plus 1 month"
</IfModule>

The problem however is that whenever we update our stylesheet or replace some images on the site, the only way for the user to see them is to actually refresh the page. We have some banners that we no longer want to show and they keep appearing on the site until there is a manual refresh.

Is there a better way to control cache?

Thanks.

1 个答案:

答案 0 :(得分:0)

You could append a query string to the resource src whenever you update it. So, your style sheet reference might look like this:

<link rel="stylesheet" type="text/css" href="theme.css">
<img src="smiley.gif" alt="Smiley face">

Then next time you update it, you could break the cache by changing the query string:

<link rel="stylesheet" type="text/css" href="theme.css?version1.2">
<img src="smiley.gif?version1.2" alt="Smiley face">

This allows you to continue working with the same filename theme.css