Typecho 首页静态化脚本 - 易维网

Typecho 首页静态化脚本

分类:随笔(Essays) ; 热度:2675 ; 最后更新于2019 年 05 月 13 日

tohnnystohnnys

主页生成静态文件html,没有嵌入主程序,完全不用担心升级问题,下面分享一下代码。

  1. 在站点根目录下创建或上传 build_index.php,访问这个文件就可以在根目录生成静态文件了。
  2. 更新缓存 http://test.com/build_index.php?password=123456可以在脚本里面设置你的密码,防止被他人利用发起CC攻击,频繁写文件造成服务器IO过高。
  3. 如果不想使用过期更新,可以从脚本里面去掉调用更新那句 script 代码,缓存过期时间修改 $expire 变量。
  4. 另外需要注意的是你的 index.html 要在 index.php 前面,否则不生效。Apache 修改 DirectoryIndex, Nginx 修改 index,IIS 配置默认文档。
<?php

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<!-- Create time: " . date( 'Y-m-d H:i:s' ) . " -->";
    //调用更新
    $content .= "n<script language=javascript src='build_index.php'></script>";
    ob_clean();//结束
    $res = file_put_contents( 'index.html', $content );
    if ( $res !== false )
    {
        die( 'Create successful' );
    }
    else
    {
        die( 'Create error' );
    }
}

GitHub下载地址:https://gist.github.com/yusureabc/34564707391b6275864b94b3cdc0088f

评论卡