Example of WordPress configuring Redis Cache for a website

Source: Internet
Author: User
Tags md5 redis ukey vars cloudflare delete cache install redis

The solution I proposed below is to cache all output HTML content in Redis without repeatedly executing the page script in WordPress. Here, using Redis instead of Varnish is easy to set and may be faster.


Install Redis

If you are using Debian or a derived operating system, run the following command to install Redis:

Apt-get install redis-server

Use Predis as the PHP client of Redis
You need a client development kit so that PHP can connect to the Redis service.

We recommend that you upload Predis. php to the WordPress root directory.

PHP scripts cached on the front end

Step 1: create a new file index-with-redis.php in the WordPress root directory with the following content:

 

The code is as follows: Copy code

<? Php
// Change vars here
$ Cf = 1; // set to 1 if you are using cloudflare
$ Debug = 0; // set to 1 if you want to see execution time and cache actions
$ Display_powered_by_redis = 1; // set to 1 if you want to display a powered by redis message with execution time, see below

$ 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 PredisClient ('');

// Init vars
$ Domain = $ _ SERVER ['http _ host'];
$ Url = "http: //". $ _ 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
(Isset ($ _ SERVER ['http _ CACHE_CONTROL ']) & $ _ 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 &&! Strpos ($ url, '/feed /')){

Echo $ redis-> hget ($ dkey, $ ukey );
$ Cached = 1;
$ 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 to cache only if the page exist and is not a search result.
If (! Is_404 ()&&! Is_search ()){
// 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 );
}

If ($ cached & $ display_powered_by_redis ){
// You shoshould move this CSS to your CSS file and change the: float: right; margin: 20px 0;
Echo "<style> # redis_powered {float: right; margin: 20px 0; background: url (yun_qi_img/redis.png) 10px no-repeat # fff; border: 1px solid # D7D8DF; padding: 10px; width: Pixel px ;}
# Redis_powered div {width: Pixel px; text-align: right; font: 10px/11px arial, sans-serif; color: #000 ;}</style> ";
Echo "<a href =" http://www.aips.me/wordpress-with-redis-as-a-frontend-cache/ "style =" text-decoration: none; "> <div id =" redis_powered "> <div> Page generated in <br/> ". t_exec ($ start, $ end ). "sec </div> </a> ";
}

// 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 );
}

?>


You can also view the index-with-redis.php on Github

Step 2: replace the IP address and domain name in the above code with the IP address and domain name of your website

Step 3: In. all indexes appear in htaccess. php is changed to index-with-redis.php, if you are using Nginx, then modify nginx. index. php is index-with-redis.php (and Nginx: killall-s HUP nginx is reloaded ).

Performance testing
When the consumer does not have Redis, the average homepage executes for 1.614 seconds and the article page executes for 0.174 seconds (no cache plug-in)
When Redis is used by the secondary node, the average page execution time is 0.00256 seconds.
I have been using the above methods in my blog for a long time, and everything works well.

Other suggestions
In this article, the author's WordPress environment is Nginx + PHP-FPM + APC + Cloudflare + Redis. Installed in a VPS, no cache plug-in.

Make sure that gzip compression is used to accelerate access.

Access wp-admin
To access wp-admin, you must use/wp-admin/index. php to replace the original/wp-admin /.


In fact, this article has already been translated in China, but I have seen that the author has been updating this article. On the contrary, domestic translators are not updated much, so I will try again.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.