加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 在CDN中进行版本控制

发布时间:2020-12-13 17:11:02 所属栏目:PHP教程 来源:网络整理
导读:是否有任何方法可以在CDN(不是Cloudfront,在本例中为Edgecast)中为js和css文件实现类似的版本控制解决方案,因为它是相当整洁的,结合了Rewrite规则和 PHP,如 this thread所述?我不知道如何让PHP / mod-rewrite组合在CDN上运行,经常更改我的版本,并且不想手动
是否有任何方法可以在CDN(不是Cloudfront,在本例中为Edgecast)中为js和css文件实现类似的版本控制解决方案,因为它是相当整洁的,结合了Rewrite规则和 PHP,如 this thread所述?我不知道如何让PHP / mod-rewrite组合在CDN上运行,经常更改我的版本,并且不想手动进行版本控制.我使用无cookie,完全独立的域来提供静态内容,因此我必须在函数中指定完整的URL.

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

首先,我们在.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函数:

/**
 *  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,我们都会改变它:

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

对此:

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

这将呈现为此类内容,确保始终提供最新版本,而无需手动更新版本:

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

为了让这个在外部CDN(在一个完全不同的域上)工作,我试图替换

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

通过这样的东西……

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

但是围绕内部URL包装函数并添加CDN域似乎不起作用……

解决方法

事实证明我的解决方案:

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

作品.我只是错过了代码中的空格.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读