알짜게시판

CDN 간단히 구축하기

  1. cdn.kilho.net 에 index.php 로 아래 코드를 저장 (.htaccess 로 존재하지 않는 파일은 index.php 로 연결)
  2. cdn.kilho.net/{파일} 로 접속시 kilho.net/{파일} 을 다운 및 캐시로 사용합니다.
<?php
    // 설정
    $cfg['url'] = 'kilho.net';
    $cfg['cache'] = '../data/cache/';

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

    if($_SERVER['REQUEST_METHOD']!='GET') 
    { 
        header('HTTP/1.0 404 File Not Found.'); 
        exit; 
    }

    $cfg['cache'] .= sha1($url_arr['host'].$url_arr['path']);

    $dirname = dirname($cfg['cache']);
    if(!is_file($cfg['cache']))
    {
        if(!is_dir($dirname)) mkdir($dirname, 0707, true);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1) Gecko/20061204 Firefox/2.0.0.1");
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accpet: */*'));
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_REFERER, $_SERVER['REQUEST_SCHEME'].'://'.$cfg['url']);
        $data = curl_exec($ch);
        $info = curl_getinfo($ch);
        curl_close($ch);

        $fp = fopen($cfg['cache'], 'w');
        fwrite($fp, $info['content_type']."\n".$data);
        fclose($fp);

        if($info['http_code']!=200)
            touch($cfg['cache'], $info['http_code']);
    }

    $filetime = filemtime($cfg['cache']);

    if($filetime<1000)
    { 
        header('HTTP/1.0 '.$filetime);
    } else {
        $lastmodified = filemtime($cfg['cache']); 
        $etag = md5_file($cfg['cache']);

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

    $fp = fopen($cfg['cache'], 'rb');
    $filetype = fgets($fp, 255);
    header('Content-Type: '.$filetype);
    while(!feof($fp)) echo fread($fp, 1024);
    fclose ($fp);
?>

로그인 후 댓글내용을 입력해주세요

제목 글쓴이 조회 날짜
개발팁 지정 폴더 내 PHP 파일 최종 수정일 확인하기 2,810 19-06-20
개발팁 CDN 간단히 구축하기 3,506 19-05-21
개발팁 파일형 멀티(?) 카운터 20,756 07-08-31
목록
책과지식클라우드AI결혼준비자기계발청년돈길