Update: Rewritten to incorporate suggestions from John Millikin and da5id .
(更新:重写以合并John Millikin和da5id的建议。)
This solution is written in PHP, but should be easily adapted to other languages.(该解决方案是用PHP编写的,但应易于适应其他语言。)
Update 2: Incorporating comments from Nick Johnson that the original .htaccess
regex can cause problems with files like json-1.3.js
.
(更新2:结合尼克·约翰逊 ( Nick Johnson)的意见,即原始的.htaccess
正则表达式可能会导致json-1.3.js
类的文件出现问题。)
Solution is to only rewrite if there are exactly 10 digits at the end.(解决方案是仅在末尾恰好有10位数字时才重写。)
(Because 10 digits covers all timestamps from 9/9/2001 to 11/20/2286.)((因为10位数字涵盖了从9/9/2001到11/20/2286的所有时间戳。))
First, we use the following rewrite rule in .htaccess:
(首先,我们在.htaccess中使用以下重写规则:)
RewriteEngine on
RewriteRule ^(.*).[d]{10}.(css|js)$ $1.$2 [L]
Now, we write the following PHP function:
(现在,我们编写以下PHP函数:)
/**
* 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:
(现在,无论您在哪里包含CSS,都可以从以下位置进行更改:)
<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.
(这样,您无需再次修改link标记,并且用户将始终看到最新的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.(浏览器将能够缓存CSS文件,但是当您对CSS进行任何更改时,浏览器会将其视为新的URL,因此它将不使用缓存的副本。)
This can also work with images, favicons, and JavaScript.
(这也可以用于图像,图标和JavaScript。)
Basically anything that is not dynamically generated.(基本上任何不是动态生成的。)