哈喽大家好,捣鼓了下博客的优化,把博客主页生成静态文件html了,没有侵入主程序,完全不用担心升级问题,下面分享一下代码。
在站点根目录下创建或上传 build_index.php,访问这个文件就可以在根目录生成静态文件了。
更新缓存 http://test.com/build_index.php?password=123456可以在脚本里面设置你的密码,防止被他人利用发起CC攻击,频繁写文件造成服务器IO过高。
如果不想使用过期更新,可以从脚本里面去掉调用更新那句 script 代码,缓存过期时间修改 $expire 变量。
另外需要注意的是你的 index.html 要在 index.php 前面,否则不生效。Apache 修改 DirectoryIndex, Nginx 修改 index,IIS 配置默认文档。
/**
* 首页静态化脚本
* Author: Yusure
* Blog: yusure.cn
*/
ini_set( 'date.timezone', 'PRC' );
/* 缓存过期时间 单位:秒 */
$expire = 86400;
/* 主动刷新密码 格式:http://test.com/build_index.php?password=123456 */
$password = '123456';
$file_time = @filemtime( 'index.html' );
time() - $file_time > $expire && create_index();
isset( $_GET['password'] ) && $_GET['password'] == $password && create_index();
/**
* 生成 index.html
*/
function create_index()
{
ob_start();
include( 'index.php' );
$content = ob_get_contents();
$content .= "\n";
/* 调用更新 */
$content .= "\n";
ob_clean();
$res = file_put_contents( 'index.html', $content );
if ( $res !== false )
{
die( 'Create successful' );
}
else
{
die( 'Create error' );
}
}