.htaccess文件内容:
RewriteEngine On
#RewriteCond %{HTTP_HOST} ^t.boss.com$
RewriteCond %{REQUEST_URI} !^$
#RewriteCond %{REQUEST_FILENAME} ^.*\.(jpg|jpeg|png|gif)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*\.jpg)$ /sync_client.php?url=$1 [NC,QSA,L]
sync_client.php文件内容:
<?php
//var_dump($_GET['url']);
//echo '<img src="http://hazy.allalla.com/inc/logo.jpg">';
$filepath = empty($_GET['url']) ? exit('no file') : $_GET['url'];
$filepath = str_ireplace('\'', '', str_ireplace('"', '', $filepath));
$filepath = str_ireplace('\\', '/', $filepath);
if(!is_file($filepath)){
$dir = dirname($filepath);
$ext = substr(strrchr( $filepath, '.' ), 1);
if(!in_array($ext, array('jpg', 'jpeg', 'gif', 'png', 'bmp'))) exit('not allow file ext');
$domain = 'http://qqqiushi.com/';//源站,你的源站必须要允许此站点访问你的图片
$url = $domain . $filepath;
$content = file_get_contents_($url);
if(strlen($content) < 20) exit('not allow content');
if(!is_dir($dir)) mkdir($dir, 0777, true);
file_put_contents($filepath, $content);
}
echo '<img src="/' . $filepath . '" />';
//获取URL的内容
function file_get_contents_($url)
{
if(empty($url)) return false;
$useragent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.168 Safari/535.19';
if(function_exists('curl_init')) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT,30);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_REFERER, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
$content = curl_exec($ch);
curl_close($ch);
}else{
$content = file_get_contents($url);
}
return $content;
}
exit;
?>
就这么简单的几句话!将两个文件放到cdn根目录:会自动将图片文件和源站图片文件的目录结构保持一致。
注:当然,如果你rewrite水平再高些,可以不带url,直接请求你要的图片或者css/js等文件,当文件不在此域名中时,然后此文件再请求源站,回显给浏览器即可。但一定要注意安全。只能请求某些文件,不可以放开。
|