关于如何生成thinkphp6的静态网页:
//多层目录创建
function mkdirs_1($path, $mode = 0777) {
if(is_dir($path)) {
return false;
} else {
if(mkdir($path, $mode, true)) {
return true;
} else {
return false;
}
}
}
//判断是否存在静态
public function beforeBuild($param = [],$type) {
//生成静态
$this->staticHtmlDir = "static-cache".DS."post".DS;
$param = $param[0][0];
$this->staticHtmlFile = $this->staticHtmlDir . $param .'.html';
//目录不存在,则创建
if(!file_exists($this->staticHtmlDir)) {
mkdir($this->staticHtmlDir,'511',true);
}
//文章不需要经常更新,静态存在一个月
if(file_exists($this->staticHtmlFile) && filectime($this->staticHtmlFile)>=time()-2626560) {
$new_url = str_replace('static-cache/','',$this->staticHtmlFile);
header("Location:/" . $new_url);
exit();
}
}
//开始生成静态文件
public function afterBuild($html) {
if(!empty($this->staticHtmlFile) && !empty($html)) {
if(file_exists($this->staticHtmlFile)) {
unlink($this->staticHtmlFile);
}
if(file_put_contents($this->staticHtmlFile,ArticleAttribute::yasuo_html($html)."n<!--生成静态时间:".date('Y年m月d日 H时i分s秒').",By html static.-->")) {
$aaaaa = str_replace('index.html','',$this->staticHtmlFile);
$new_url = str_replace('static-cache/','',$aaaaa);
header("Location:/" . $new_url);
exit();
}
}
}
/**
* 文章页生成静态
*/
public function getList($id = '',$view,$type) {
//判断静态界面是否存在
$this->beforeBuild(array($id),$type);
// do someing
$name = "测试静态化";
$html = View::fetch($view,['name'=>$name]);
//生成静态界面
$this->afterBuild($html);
}
把上面的代码放在一个公共类里面即可,之后在对应的操作分组中调用,把需要的参数传输过来就行。
// 执行生成静态
$kaiqi=sysconfig('system','jingtai');
if($kaiqi == 1){
$jingtai->getIndex('首页','/index_index','html');
}else{
return ArticleAttribute::yasuo_html($this->fetch());
}
先获取系统的设置,$kaiqi 如果值为 1 ,则进行静态,值为 0 ,则动态输出。
需要说明一下,上面的代码还有完善空间,如果直接放在网页的默认目录下面,代码还可以精简,像重定向这些就不需要切割多余的路径,直接定向 $this->staticHtmlFile 这个就行,在新能上要更好一点。
生成之后基本上所有的访问都是通过 Location 重定向完成的。
使用 Nginx 伪静态规则定义:
beforeBuild 方法中,重定向也不需要了,直接通过我下面的nginx规则就能访问,afterBuild 方法中的定向需要原样保持,因为生成文件之后运行依旧在这个方法中,不进行重定向就无法正常访问网页,除非在 getList 方法最下面加重定向,这种方法多次一举。后续访问都直接通过nginx伪静态规则忽略掉static-cache目录和index.html,保持动态一致的路径。
location / {
gzip_static always;
gunzip on;
if (-f $request_filename) {
break;
}
if ($uri ~ /(.*)$){
set $wpuri $1;
set $sscfile $document_root/static-cache/$1;
}
set $ssc Y;
if ($query_string !~ .*=.*){
set $ssc "${ssc}Y";
}
if ($request_method != "POST"){
set $ssc "${ssc}Y";
}
if (-f $sscfile){
set $ssc "${ssc}F";
}
if (-f $sscfile/index.html){
set $ssc "${ssc}I";
}
if ($ssc = YYYF){
rewrite . /static-cache/$wpuri break;
}
if ($ssc = YYYI){
rewrite . /static-cache/$wpuri/index.html break;
}
if (!-e $request_filename){
rewrite ^/(d+).html http://$host/post/$1.html permanent;
rewrite ^/html/(d+).html http://$host/post/$1.html permanent;
rewrite ^(.*)$ /index.php?s=$1 last; break;
}
}
至此,就是我初步在thinkphp6上实现的真正的静态化网站。
正文结束