Consider the following CSS:
.my_class {
background-image: url(/images/sprites.png);
}
Sometimes I change sprites.png
by adding new sprites to it, so I don't want the browser to cache it.
One idea I thought of is to add style="background-image: url(/images/sprites.png?<random_number_here>)"
to all elements with class my_class
, and delete the CSS code above.
But, I don't like this solution because of maintainability issues (if for example the file name changes, I have to change it in many places, rather than a single CSS).
What other solutions exist to this problem ?
One way around this is to add a version string to your style directory.
<link rel="stylesheet" href="/css.1000/styles.css" type="text/css" />
Ensure that your css uses URLs relative to that directory. (In this example, the image directory for css links is css.1000/image
)
.my_class {
background-image: url(images/sprites.png);
}
Then, use mod_rewrite
to add a rewrite rule to the .htaccess
file in your site's root folder, this will make any numerical path /css.1000/styles.css
point to /css/styles.css
on the server:
RewriteEngine On
RewriteRule css[\.][0-9]+/(.*)$ css/$1 [L]
Any time you change your site's assets, you change the version number of the folder in your stylesheet link.