简单静态资源分发脚本

网站静态资源太多的情况下有时候我们需要分成多个域名来请求这些静态资源。
如原来我们使用的

http://static.ioio.name/upload/hello.jpg

改成随机的使用

http://s1.ioio.name/upload/hello.jpg
http://s2.ioio.name/upload/hello.jpg
http://s3.ioio.name/upload/hello.jpg

这时候我们需要将s1/s2/s3服务器上的文件跟源服务器static同步。以使得他们都是访问的static上同名文件的拷贝。

这里我写了一段简单的php脚本采用溯源的策略来更新这些文件,当s1/s2/s3服务器上不存在该文件的时候,就向源服务器(static)请求该文件,并且保存在本地cache一份以便后续的相同请求使用。

1.在s1/s2/s3服务器上添加名为cdn.php的文件,内容如下:

<?php
$path = $_GET["name"];
$filename = md5($path);
$file = "save/".$filename.".data";
if(file_exists($file)){
	header('Content-type: '.mime_content_type($file));
	echo file_get_contents($file);
}else{
	$content = file_get_contents("http://source.ioio.name/upload/".$path);
	file_put_contents($file,$content);
	header('Content-type: '.mime_content_type($file));
	echo $content;
}
?>

这段脚本会将读取到的文件存在本地的save文件夹里,需要save文件夹的读写权限。

2.配置.htaccess文件,添加一行记录:

RewriteRule ^upload/(.*)$ /cdn.php?name=$1 [L]

这样配置后s1/s2/s3就能按照static的路径规则访问到相同的文件了。在实际的生成环境,可能会需要更复杂的cache策略,这里就不深入讨论。
-EOF-