How to set up caching for css/js static properly

断了今生、忘了曾经 提交于 2019-12-01 13:12:11

You should use proper HTTP caching directives to make the responses never expire (one year in future):

Cache-Control: max-age=31536000
Expires: Sun, 24 Jul 2012 12:51:05 GMT

You can do this in Apache with mod_expires:

ExpiresByType text/css "now plus 1 year"
ExpiresByType text/javascript "now plus 1 year"


I played with this a lot and I found that it is probably caused by an Apache bug. This is not problem of the browser - once the timesatmp is in a query string, the browser doesn't understand the query string and must at least ask the server if it hasn't changed. The Apache responds well with '304 Not modified', but it always sends the file too!

I made a lot of experiment and the only solution that worked was to place the timestamp directly to file name. In PHP, I use the following function:

function safe_inline_url($file)
{

     $basename = basename($file);
     if (strstr($basename, '.'))
          return dirname($file) . "/" .
               preg_replace('/(\.[^\.]*)$/', '_ts_' . filemtime($file) . '\1',
                    $basename);
     else 
          return $file . '_ts_' . filemtime($file);

}

which modifies any inline URL (css, js, images, ...) so that it adds timestamp, eg. like js/forms.js => js/forms_ts_1278080148.js .

At the server, you must then rewrite the modified filenames back to the real names, which is accomplished by putting this to your .htaccess file:

RewriteEngine On

RewriteCond %{REQUEST_URI}      ^(.*)_ts_[0-9]{9,}$
RewriteRule ^                   %1      [PT]

RewriteCond %{REQUEST_URI}      ^(.*)_ts_[0-9]{9,}\.(.*)$
RewriteRule ^                   %1.%2   [PT]

you put it to root directory and you also must put it to every subdirectory's .htaccess with RewriteEngine On.

The only issue was with scriptaculous javascript library which uses URLs to include other sources - you cannot use this trick to include their js files.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!