wordpress速度毫秒级优化-redis终极加速-比任何缓存插件都快的方法
有些朋友的网站搭建在一个比较差的服务器上,所以速度可想而知是非常的不怎么快。但是速度就是流量,3秒内打不开基本就没啥人原因等了。
所以,我们还是想尽最大努力再救一下,对于wordpress建的站有很多优化插件可以用,但是效果都有限。
前期摸索
部署好网站之后我就开启了mencached缓存,开启后速度也还是不尽如人意。
然后又尝试使用了大家最常用的缓存插件,如W3 Total Cache插件、WP super cache插件,但是由于服务器基础不好,这些插件的作用也不怎么明显。
再后来又安装了redis缓存,宝塔面板下非常容易,就是先安装redis服务器,再到PHP中安装redis扩展。网上一大堆教程我就不重复了,不会的去度娘一下。
到这里大家的网站应该可以比较快了,3秒以内打开已经非常有可能了。
但是我的还是速度很慢,基本都要3秒。
终极加速(毫秒级)
后来,各种搜索,终于发现了一种终极加速方法,也是我目前在用的,可以实现0.00X秒速度。
这种方法也是redis缓存,但是使用的客户端和前面的不一样,是使用Predis.php作为客户端,前端使用了Jim Westergren开发的index-with-redis.php

具体使用方法:
1.下载Predis.php,将该php文件放到网站根目录。
Predis.php下载https://eeimicom.lanzouw.com/i6azruht21e
2.在 WordPress 的根目录创建新文件 index-with-redis.php ,内容如下:
<?php
/*
author: jeedo aquino
file: wp-index-redis.php
credit: jim westergren
updated: 2012-10-23
this is a redis caching system for wordpress inspired by jim westergren.
see more here: www.jimwestergren.com/wordpress-with-redis-as-a-frontend-cache/
some caching mechanics are different from jim's script which is summarized below:
- cached pages do not expire not unless explicitly deleted or reset
- appending a ?c=y to a url deletes the entire cache of the domain, only works when you are logged in
- appending a ?r=y to a url deletes the cache of that url
- script still works even if allow_fopen is disabled
- submitting a comment deletes the cache of that page
- refreshing (f5) a page deletes the cache of that page
- includes a debug mode, stats are displayed at the bottom most part after
for setup and configuration see more here:
www.jeedo.net/lightning-fast-wordpress-with-nginx-redis/
use this script at your own risk. i currently use this albeit a slightly modified version
to display a redis badge whenever a cache is displayed.
*/
// change vars here
$cf = 0; // set to 1 if you are using cloudflare
$debug = 1; // set to 1 if you wish to see execution time and cache actions
$start = microtime(); // start timing page exec
// if cloudflare is enabled
if ($cf) {
if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {
$_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_CF_CONNECTING_IP'];
}
}
// from wp
define('WP_USE_THEMES', true);
// init predis
include("predis.php");
$redis = new Predis\Client('');
// init vars
$domain = $_SERVER['HTTP_HOST'];
$url = "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$url = str_replace('?r=y', '', $url);
$url = str_replace('?c=y', '', $url);
$dkey = md5($domain);
$ukey = md5($url);
// check if page isn't a comment submission
(($_SERVER['HTTP_CACHE_CONTROL'] == 'max-age=0') ? $submit = 1 : $submit = 0);
// check if logged in to wp
$cookie = var_export($_COOKIE, true);
$loggedin = preg_match("/wordpress_logged_in/", $cookie);
// check if a cache of the page exists
if ($redis->hexists($dkey, $ukey) && !$loggedin && !$submit) {
echo $redis->hget($dkey, $ukey);
if (!$debug) exit(0);
$msg = 'this is a cache';
// if a comment was submitted or clear page cache request was made delete cache of page
} else if ($submit || substr($_SERVER['REQUEST_URI'], -4) == '?r=y') {
require('./wp-blog-header.php');
$redis->hdel($dkey, $ukey);
$msg = 'cache of page deleted';
// delete entire cache, works only if logged in
} else if ($loggedin && substr($_SERVER['REQUEST_URI'], -4) == '?c=y') {
require('./wp-blog-header.php');
if ($redis->exists($dkey)) {
$redis->del($dkey);
$msg = 'domain cache flushed';
} else {
$msg = 'no cache to flush';
}
// if logged in don't cache anything
} else if ($loggedin) {
require('./wp-blog-header.php');
$msg = 'not cached';
// cache the page
} else {
// turn on output buffering
ob_start();
require('./wp-blog-header.php');
// get contents of output buffer
$html = ob_get_contents();
// clean output buffer
ob_end_clean();
echo $html;
// store html contents to redis cache
$redis->hset($dkey, $ukey, $html);
$msg = 'cache is set';
}
$end = microtime(); // get end execution time
// show messages if debug is enabled
if ($debug) {
echo $msg.': ';
echo t_exec($start, $end);
}
// time diff
function t_exec($start, $end) {
$t = (getmicrotime($end) - getmicrotime($start));
return round($t,5);
}
// get time
function getmicrotime($t) {
list($usec, $sec) = explode(" ",$t);
return ((float)$usec + (float)$sec);
}
?>
或者直接下载index-with-redis.php
3.如果你的服务器环境是Apache,则在 .htaccess 中将所有出现 index.php 的地方改为 index-with-redis.php ,如果你使用的是 Nginx 则重命名index-with-redis.php的 index.php (原index.php请备份)。
优化完毕,接下来在访问你的网站,你会发现已经飞起来了。
后话
前文的index-with-redis.php经过优化之后的,推荐优先使用,但是有些情况下可能会出现错误现象,比如我使用上面的index-with-redis.php后内页都很正常,但是首页经常无法加载样式。
所以我就使用了index-with-redis.php最原始版本,目前情况待观测。
原始版本index-with-redis.php代码如下
<?php
// Change these two variables:
$seconds_of_caching = 60*60*24*7; // 7 days.
$ip_of_this_website = '1.1.1.1'; // 此处更换为你的服务器ip
/*
- This file is written by Jim Westergren, copyright all rights reserved.
- See more here: www.jimwestergren.com/wordpress-with-redis-as-a-frontend-cache/
- The code is free for everyone to use how they want but please mention my name and link to my article when writing about this.
- Change $ip_of_this_website to the IP of your website above.
- Add ?refresh=yes to the end of a URL to refresh it's cache
- You can also enter the redis client via the command prompt with the command "redis-cli" and then remove all cache with the command "flushdb".
*/
// Very necessary if you use Cloudfare:
if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {
$_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_CF_CONNECTING_IP'];
}
// This is from WordPress:
define('WP_USE_THEMES', true);
// Start the timer:
function getmicrotime($t) {
list($usec, $sec) = explode(" ",$t);
return ((float)$usec + (float)$sec);
}
$start = microtime();
// Initiate redis and the PHP client for redis:
include("predis.php");
$redis = new Predis\Client('');
// few variables:
$current_page_url = "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$current_page_url = str_replace('?refresh=yes', '', $current_page_url);
$redis_key = md5($current_page_url);
// This first case is either manual refresh cache by adding ?refresh=yes after the URL or somebody posting a comment
if (isset($_GET['refresh']) || substr($_SERVER['REQUEST_URI'], -12) == '?refresh=yes' || ($_SERVER['HTTP_REFERER'] == $current_page_url && $_SERVER['REQUEST_URI'] != '/' && $_SERVER['REMOTE_ADDR'] != $ip_of_this_website)) {
require('./wp-blog-header.php');
$redis->del($redis_key);
// Second case: cache exist in redis, let's display it
} else if ($redis->exists($redis_key)) {
$html_of_current_page = $redis->get($redis_key);
echo $html_of_current_page;
echo "<!-- This is cache -->";
// third: a normal visitor without cache. And do not cache a preview page from the wp-admin:
} else if ($_SERVER['REMOTE_ADDR'] != $ip_of_this_website && strstr($current_page_url, 'preview=true') == false) {
require('./wp-blog-header.php');
$html_of_current_page = file_get_contents($current_page_url);
$redis->setex($redis_key, $seconds_of_caching, $html_of_current_page);
echo "<!-- Cache has been set -->";
// last case: the normal WordPress. Should only be called with file_get_contents:
} else {
require('./wp-blog-header.php');
}
// Let's display some page generation time (note: CloudFlare may strip out comments):
$end = microtime();
$t2 = (getmicrotime($end) - getmicrotime($start));
if ($_SERVER['REMOTE_ADDR'] != $ip_of_this_website) {
echo "<!-- Cache system by Jim Westergren. Page generated in ".round($t2,5)." seconds. -->";
}
?>


本文系作者 @siqing 原创发布在 思晴·思暖。未经许可,禁止转载。
确实提升很明显