Jump to content
新域网络技术论坛
Sign in to follow this  
Jamers

PHP使用强制304缓存静态文件

Recommended Posts

很多情况下,用户频繁请求文件,会带走很多流量,其实有的时候根本没必要请求,怎么办呢?通过rewrite把所有的请求集中管理起来,判断有没有缓存,没缓存强制设置缓存,另外检查本地修改时间,如果已经修改直接更新,就是不知道上传到服务器上去的文件修改时间会不会一起改变,待测试!

/*
RewriteEngine on
#RewriteBase /Test/
RewriteCond %{REQUEST_FILENAME} ^.*?\.(css|js|jpg|png)$
RewriteRule ^(.*)$ p304.php/$1 [QSA,PT,L]
*/
//静态文件尝试使用304方式优化
//缓存时间10年
$cache_time = 315360000;
$root = $_SERVER['DOCUMENT_ROOT'];
$file = $_SERVER['REQUEST_URI'];
if (isset($_SERVER['REDIRECT_URL'])) {
    $file = $_SERVER['REDIRECT_URL'];
}else{
    $f = explode('?',$file);
    $file = $f[0];
}

if (file_exists($root.$file)) {
    $is304 = false;
    if (isset($_SERVER["HTTP_IF_MODIFIED_SINCE"])) {
        $lt = strtotime($_SERVER["HTTP_IF_MODIFIED_SINCE"]);
        $ft = filemtime($root.$file);
        if ($ft <= $lt) $is304 = true;
    }
    if ($is304) {
        header($_SERVER["SERVER_PROTOCOL"].' 304 Not Modified');
        header("Cache-Control: max-age=$cache_time");
    }else{
        header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
        header("Expires: " . gmdate("D, d M Y H:i:s", time() + $cache_time) . " GMT");
        header("Cache-Control: max-age=$cache_time");
        echo(file_get_contents($root . $file));
    }
}else{
    header($_SERVER["SERVER_PROTOCOL"].' 404 Not Found');
}

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...