This solution is written in PHP, but it should be easily adapted to other languages.
The original .htaccess
regex can cause problems with files like json-1.3.js
. The solution is to only rewrite if there are exactly 10 digits at the end. (Because 10 digits covers all timestamps from 9/9/2001 to 11/20/2286.)
First, we use the following rewrite rule in .htaccess:
RewriteEngine on
RewriteRule ^(.*)\.[\d]{10}\.(css|js)$ $1.$2 [L]
Now, we write the following PHP function:
/**
* Given a file, i.e. /css/base.css, replaces it with a string containing the
* file's mtime, i.e. /css/base.1221534296.css.
*
* @param $file The file to be loaded. Must be an absolute path (i.e.
* starting with slash).
*/
function auto_version($file)
{
if(strpos($file, '/') !== 0 || !file_exists($_SERVER['DOCUMENT_ROOT'] . $file))
return $file;
$mtime = filemtime($_SERVER['DOCUMENT_ROOT'] . $file);
return preg_replace('{\\.([^./]+)$}', ".$mtime.\$1", $file);
}
Now, wherever you include your CSS, change it from this:
<link rel="stylesheet" href="/css/base.css" type="text/css" />
To this:
<link rel="stylesheet" href="<?php echo auto_version('/css/base.css'); ?>" type="text/css" />
This way, you never have to modify the link tag again, and the user will always see the latest CSS. The browser will be able to cache the CSS file, but when you make any changes to your CSS the browser will see this as a new URL, so it won't use the cached copy.
This can also work with images, favicons, and JavaScript. Basically anything that is not dynamically generated.
Use the CSS 3 property background-size
:
#my_container {
background-size: 100% auto; /* width and height, can be %, px or whatever. */
}
This is available for modern browsers, since 2012.
Best Answer
I just had the same problem with JSF 2.0. I had to use a CSS and the solution with the relative path didn't work for me either (like Choghere posted).
In my book I read that when you use Facelets as VDL (View Declaration Language) it is possible to use expressions even in a plain HTML page. So I got the idea to put a EL directly in my CSS. Note: I didn't have to change the filename or anything.
Here is what I did. but first my filestructure:
Now here comes the CSS:
in this case resource is an implicit object of JSF 2, images is the library where JSF should look (jsf expects all libraries/files under resources, at least the default ResourceHandler) and then the name of the resource.
For deeper structures it would be:
Hope that helps ;)