wordpress生成静态缓存文件提高访问速度
文章目录
自从用了wordpress程序建站后,很多功能都是可以开发的,比如我现在使用的是伪静态功能。这个功能就会导致在某些服务器上打开的速度很慢,当然不是服务器宽带不够,可能是因为获取数据的时候太慢了,导致网站的访问速度变慢了。
解决wordpress伪静态访问很慢的办法:
wordpress生成静态缓存
1、创建一个cache.php文件
将下面代码放在这个文件中,并上传至程序的根目录
<?php
define('CACHE_ROOT', dirname(__FILE__).'/cache');
define('CACHE_LIFE', 86400); //缓存文件的生命期,单位秒,86400秒是一天
define('CACHE_SUFFIX','.html'); //缓存文件的扩展名,千万别用 .php .asp .jsp .pl 等等
$file_name = md5($_SERVER['REQUEST_URI']).CACHE_SUFFIX; //缓存文件名
//缓存目录,根据md5的前两位把缓存文件分散开。避免文件过多。如果有必要,可以用第三四位为名,再加一层目录。
//256个目录每个目录1000个文件的话,就是25万个页面。两层目录的话就是65536*1000=六千五百万。
//不要让单个目录多于1000,以免影响性能。
$cache_dir = CACHE_ROOT.'/'.substr($file_name,0,2);
$cache_file = $cache_dir.'/'.$file_name; //缓存文件存放路径
if($_SERVER['REQUEST_METHOD']=='GET'){ //GET方式请求才缓存,POST之后一般都希望看到最新的结果
if(file_exists($cache_file) && time() - filemtime($cache_file) < CACHE_LIFE){ //如果缓存文件存在,并且没有过期,就把它读出来。
$fp = fopen($cache_file,'rb');
fpassthru($fp);
fclose($fp);
exit();
}
elseif(!file_exists($cache_dir)){
if(!file_exists(CACHE_ROOT)){
mkdir(CACHE_ROOT,0777);
chmod(CACHE_ROOT,0777);
}
mkdir($cache_dir,0777);
chmod($cache_dir,0777);
}
function auto_cache($contents){ //回调函数,当程序结束时自动调用此函数
global $cache_file;
$fp = fopen($cache_file,'wb');
fwrite($fp,$contents);
fclose($fp);
chmod($cache_file,0777);
clean_old_cache(); //生成新缓存的同时,自动删除所有的老缓存。以节约空间。
return $contents;
}
function clean_old_cache(){
chdir(CACHE_ROOT);
foreach (glob("*/*".CACHE_SUFFIX) as $file){
if(time()-filemtime($file)>CACHE_LIFE){
unlink($file);
}
}
}
ob_start('auto_cache'); //回调函数 auto_cache
}
else{
if(file_exists($cache_file)){ //file_exists() 函数检查文件或目录是否存在。
unlink($cache_file); //不是GET的请求就删除缓存文件。
}
}
?>
2.在根目录创建一个文件夹,命名为cache
如下图

3.打开根目录的index.php文件,在<?php后面添加代码
换行,添加require(‘cache.php’);代码,加好了的效果如下:
<?php
require('cache.php');
/**
* Front to the WordPress application. This file doesn't do anything, but loads
* wp-blog-header.php which does and tells WordPress to load the theme.
*
* @package WordPress
*/
/**
* Tells WordPress to load the WordPress theme and output it.
*
* @var bool
*/
define( 'WP_USE_THEMES', true );
/** Loads the WordPress Environment and Template */
require __DIR__ . '/wp-blog-header.php';
通过上面的方法,就可以实现网页缓存了,这个缓存文件是放在服务器上的,但是前段访问过的文件,后台才会生成临时缓存文件,如果重来都没有访问过,就不会生产缓存文件。
版权保护: 本文由小冬SEO编辑发布,转载请保留链接: http://www.myseoyh.cn/shuo/128.html
- 上一篇: wordpress分类和文章指定模板
- 下一篇:wordpress创建搜索页