I used CloudFlare to reduce traffic load, but found that the connection was much slower because its location was LAX (Los Angeles), so I quickly made this to use as a CDN.
The server is located in Tokyo (Vultr).
The idea is to redirect kilho.net/{file} to cdn.kilho.net/{file} to distribute traffic from the main host.
[PHP]
<?
$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.‘);
?>
[/PHP]



eeee