CDN中的版本控制 [英] Versioning in a CDN

查看:72
本文介绍了CDN中的版本控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何方法可以在CDN(在这种情况下为 not Cloudfront,在此为Edgecast)的CDN上实现类似的版本控制解决方案,将jscss文件作为整洁的文件,结合重写规则和PHP,在

Is there any way of achieving a similar versioning solution on a CDN (not Cloudfront, Edgecast in this case) for js and css files as the rather neat one, combining a Rewrite rule and PHP, described in this thread? I don't know of a way of making that PHP/mod-rewrite combination work on a CDN, change my versions often, and don't want to do the versioning manually. I use a cookieless, entirely separate domain to serve static content, so I have to specify the full url in the function.

为方便起见,我将在此处列出其他线程的代码.

For convenience I'll set out the code from the other thread here.

首先,我们在.htaccess中使用以下重写规则:

First, we use the following rewrite rule in .htaccess:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-s # Make the file doesn't actually exist
RewriteRule ^(.*)\.[\d]+\.(css|js)$ $1.$2 [L] # Strip out the version number

现在,我们编写以下PHP函数:

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);
}

现在,无论我们在哪里包含CSS,我们都会对此进行更改:

Now, wherever we include our CSS, we change it from this:

<link rel="stylesheet" href="/css/base.css" type="text/css" />

对此:

<link rel="stylesheet" href="<?=auto_version('/css/base.css')?>" type="text/css" />

这将呈现为这种形式,从而确保始终提供最新版本,而无需手动更新版本:

This will render as something of this kind, ensuring the latest version is always served, without having to update versions manually:

<link rel="stylesheet" href="/css/base.1251992914.css" type="text/css" />

为了使它在外部CDN(完全不同的域)上工作,我尝试替换

In order to get this working in an external CDN (on a totally different domain), I've tried to replace

<link rel="stylesheet" href="<?=auto_version('/css/base.css')?>" type="text/css" />

通过这样的东西...

by something like this...

<link rel="stylesheet" href="<?='http://cdn.externaldomain.com' . auto_version('/css/base.css')?>" type="text/css" />

但是将函数包装在内部URL周围并添加CDN域似乎不起作用...

But wrapping the function around the internal URL and adding the CDN domain doesn't seem to work...

推荐答案

原来是我的解决方案:

<link rel="stylesheet" href="<?= 'http://cdn.externaldomain.com' . auto_version('/css/base.css') ?>" type="text/css" />

有效.我只是错过了代码中的空格.

works. I'd just missed out a space in the code.

这篇关于CDN中的版本控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆