用PHP制作简单的CDN服务模块

CloudFlare的使用,以减少交通负荷连接位置LAX(洛杉矶)LA的确认过程,你慢下来了很多,创造了一个急于使用CDN形式。

网站服务器位于东京(Vultr)。

其原理是连接kilho.net/ {}文件到cdn.kilho.net/~~V {}文件分发主托管的流量。


<?
$cfg['url'] = 'kilho.net';
$cfg['cache'] = '../data/cache';

$url = $_SERVER['REQUEST_SCHEME'].'://'.$cfg['url'].$_SERVER['REQUEST_URI'];
$url_arr = parse_url($url);

switch($_SERVER['REQUEST_METHOD'])
{
case 'GET':
$filename = $cfg['cache'].$url_arr['path'];
$dirname = dirname($filename);
if(!is_file($filename))
{
if(!is_dir($dirname)) mkdir($dirname, 0707, true);

$ch = curl_init();
$fp = fopen($filename, 'w');
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_REFERER, $_SERVER['REQUEST_SCHEME'].'://'.$cfg['url']);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_exec($ch);
fclose($fp);

switch($code = curl_getinfo($ch, CURLINFO_HTTP_CODE))
{
case 200:
break;

default:
touch($filename, $code);
}
curl_close($ch);
}

if(is_file($filename))
{
$filetime = filemtime($filename);

if($filetime<1000)
{
header('HTTP/1.0 '.$filetime);
} else {
include '_mime.php';
$filetype = get_mime($filename);
$lastmodified = filemtime($filename);
$etag = md5_file($filename);

header('Content-Type: '.$filetype);
header('Expires: '.gmdate('D, d M Y H:i:s', time()+77760000).' GMT');
header('Cache-Control: public, max-age=77760000');
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $lastmodified).' GMT');
header('Etag: '.$etag);
header('Access-Control-Allow-Origin: *');

if(isset($_SERVER['HTTP_IF_MODIFIED_SINCE']))
{
if($_SERVER['HTTP_IF_MODIFIED_SINCE']==gmdate('D, d M Y H:i:s', $lastmodified).' GMT'||$_SERVER['HTTP_IF_NONE_MATCH']==$etag)
{
header('HTTP/1.0 304 Not Modified');
exit;
}
}
}

if(strstr($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip'))
if(in_array($filetype, array('text/plain', 'text/html', 'text/css', 'text/javascript', 'application/json', 'application/xml')))
ob_start('ob_gzhandler');

$fp = fopen($filename, 'rb');
fpassthru($fp);
fclose ($fp);

exit;
}

break;

case 'POST':

case 'PUT':

case 'DELETE';
break;
}

header('HTTP/1.0 404 File Not Found.');
?>

arrow