2016-04-21 16:44:45 0 Comments CDN Boy.Lee

Use PHP and Nginx to control CDN refresh time

In Web dev, we usually put pic file, css file and js file to CDN server to faster load speed, it's an advtange of CDN, but sometime we need face this too: usually we need wait 5 hours, 10 hours, 20 hours or longer to wait CDN refresh, maybe some CDN provider has manual refresh, but it's all need waitting time.

It's not acceptable, after research we found, we can use PHP+Nginx to control CDN refresh time, it will code only 0 secs for CDN refresh, and you can control when the refresh happen, sound good? let's see how it work!

 

{Design Part} 

//Normal
URL:http://r.yiilib.com/site/css/main.css

//force refresh
URL:http://r.yiilib.com/site/css/v001/main.css

可以看出差别在于我们把版本号v001放到了url里面, 那么当CDN计算的时候会默认为v001/main.css 和 v002/main.css两个文件, 通过这样的原理就可以实现CND刷新时间控制了, 下面来看PHP和Nginx如何实现

 

{PHP Part}

$versionNum = 'v001';

  <link rel="stylesheet" type="text/css" href="http://r.yiilib.com/site/css/<?php echo $versionNum; ?>/main.css">

 

{Nginx Part}

location ~^/(css|js)/v.*/.*(css|js)$ {
    rewrite ^(/(css|js)/)v.*/(.*)$ $1$3 break;
}

mapping relation:

location ~^/(css|js)/v.*/.*(css|js)$ => found /css/v001/main.css

$1 => (/(css|js)/) => /css/
$2 => (css|js) => css
$3 => (.*) => main.css

$1$3 => /css/main.css

 

{CDN Part}

Yep, we need found the old files and delete it, search /css/v001 found all files for v001 and delete it.

 

{Analysis}

Advantage: CDN Faster refresh, no need wait, very good for new project.

Disadvantage: Need manual delete file, need manual change version number

 

{总结}

还是比较推荐这样做的, 随心所欲的刷新CDN, 基本做到了鱼与熊掌.

如果有更好的方式或Bug欢迎留言