前几天逛typecho论坛的时候发现了typecho首页静态化的方案,对于网站而言,打开首页的速度决定用户的体验,网站速度超过3秒用户大概率选择离开网站。将动态的首页生成静态化(HTML)就可以极大的提升网站的打开速度。生成后速度确实提升很大。如果有太多动态的内容,可能生成出来会导致页面异常。

无密码生成HTML

 1<?php
 2$nowtime=time();
 3$pastsec = $nowtime - $_GET["t"];
 4if($pastsec<600)
 5{
 6exit; //10分钟更新一次,时间可以自己调整
 7}
 8ob_start(); //打开缓冲区
 9include("index.php");
10$content = ob_get_contents(); //得到缓冲区的内容
11$content .= "\n<script language=javascript src=\"new_html.php?t=".$nowtime."\"></script>"; //加上调用更新程序的代码
12file_put_contents("index.html",$content);
13if (!function_exists("file_put_contents"))
14{
15function file_put_contents($fn,$fs)
16{
17$fp=fopen($fn,"w+");
18fputs($fp,$fs);
19fclose($fp);
20}
21}

有密码生成HTML

作者博客:于帅博客

 1<?php
 2/**
 3 * 首页静态化脚本
 4 * Author: Yusure
 5 * Blog: yusure.cn
 6 */
 7ini_set( 'date.timezone', 'PRC' );
 8 
 9/* 缓存过期时间 单位:秒 */
10$expire = 86400;
11/* 主动刷新密码  格式:http://test.com/build_index.php?password=123456 */
12$password = '123456';
13$file_time = @filemtime( 'index.html' );
14time() - $file_time > $expire && create_index();
15isset( $_GET['password'] ) && $_GET['password'] == $password && create_index();
16 
17/**
18 * 生成 index.html
19 */
20function create_index()
21{
22    ob_start();
23    include( 'index.php' );
24    $content = ob_get_contents();
25    $content .= "\n<!-- Create time: " . date( 'Y-m-d H:i:s' ) . " -->";
26    /* 调用更新 */
27    $content .= "\n<script language=javascript src='build_index.php'></script>";
28    ob_clean();
29    $res = file_put_contents( 'index.html', $content );
30    if ( $res !== false )
31    {
32        die( 'Create successful' );
33    }
34    else
35    {
36        die( 'Create error' );
37    }
38}
  • 把其中一段代码以UTF8编码保存为build_index.php 访问就可以在目录生成缓存文件。
  • 把首页默认文档优先级设置为index.html为第一位。

不需要密码脚本的链接:https://你的域名/build_index.php 需要密码脚本的链接:https://你的域名/build_index.php?password=123456

无密码脚本

查看首页代码,末尾出现<script language=javascript>......之类的字眼,说明你访问的就是index.html的页面。

有密码脚本

查看首页代码,末尾出现缓存的最后一次的更新时间。

1<!-- Create time: 2020-12-12 00:00:59 -->
2<script language=javascript src='build_index.php'></script>

说明你访问的是HTML的页面。