Report this

What is the reason for this report?

How To Configure Redis Caching to Speed Up WordPress on Ubuntu 14.04

Published on December 15, 2014
How To Configure Redis Caching to Speed Up WordPress on Ubuntu 14.04

Introduction

Redis is an open-source key value store that can operate as both an in-memory store and as cache. Redis is a data structure server that can be used as a database server on its own, or paired with a relational database like MySQL to speed things up, as we’re doing in this tutorial.

For this tutorial, Redis will be configured as a cache for WordPress to alleviate the redundant and time-consuming database queries used to render a WordPress page. The result is a WordPress site which is much faster, uses less database resources, and provides a tunable persistent cache. This guide applies to Ubuntu 14.04.

While every site is different, below is an example benchmark of a default Wordpress installation home page with and without Redis, as configured from this guide. Chrome developer tools were used to test with browser caching disabled.

Default WordPress home page without Redis:

804ms page load time

Default WordPress home page with Redis:

449ms page load time

Note: This implementation of Redis caching for WordPress relies on a well-commented but third-party script. The script is hosted on DigitalOcean’s asset server, but was developed externally. If you would like to make your own implementation of Redis caching for WordPress, you will need to do some more work based on the concepts presented here.

Redis vs. Memcached

Memcached is also a popular cache choice. However, at this point, Redis does everything Memcached can do, with a much larger feature set. This Stack Overflow page has some general information as an overview or introduction to persons new to Redis.

How does the caching work?

The first time a WordPress page is loaded, a database query is performed on the server. Redis remembers, or caches, this query. So, when another user loads the Wordpress page, the results are provided from Redis and from memory without needing to query the database.

The Redis implementation used in this guide works as a persistent object cache for WordPress (no expiration). An object cache works by caching the SQL queries in memory which are needed to load a WordPress page.

When a page loads, the resulting SQL query results are provided from memory by Redis, so the query does not have to hit the database. The result is much faster page load times, and less server impact on database resources. If a query is not available in Redis, the database provides the result and Redis adds the result to its cache.

If a value is updated in the database (for example, a new post or page is created in WordPress) the Redis value for that query is invalidated to prevent bad cached data from being presented.

If you run into problems with caching, the Redis cache can be purged by using the flushall command from the Redis command line:

redis-cli

Once you see the prompt, type:

flushall

Additional Reference: WordPress Object Cache Documentation

Prerequisites

Before starting this guide, you’ll need to set up a sudo user and install WordPress.

  • Ubuntu 14.04 Droplet (1 GB or higher recommended)
  • Add a sudo user
  • Install WordPress. This guide has been tested with these instructions, although there are many ways to install WordPress

Step 1 — Install Redis

In order to use Redis with WordPress, two packages need to be installed: redis-server and php5-redis. The redis-server package provides Redis itself, while the php5-redis package provides a PHP extension for PHP applications like WordPress to communicate with Redis.

Install the softare:

sudo apt-get install redis-server php5-redis

Step 2 — Configure Redis as a Cache

Redis can operate both as a NoSQL database store as well as a cache. For this guide and use case, Redis will be configured as a cache. In order to do this, the following settings are required.

Edit the file /etc/redis/redis.conf and add the following lines at the bottom:

sudo nano /etc/redis/redis.conf

Add these lines at the end of the file:

maxmemory 256mb
maxmemory-policy allkeys-lru

When changes are complete, save and close the file.

Step 3 — Obtain Redis Cache Backend Script

This PHP script for WordPress was originally developed by Eric Mann. It is a Redis object cache backend for WordPress.

Download the object-cache.php script. This download is from DigitalOcean’s asset server, but this is a third-party script. You should read the comments in the script to see how it works.

Download the PHP script:

wget https://assets.digitalocean.com/articles/wordpress_redis/object-cache.php

Move the file to the /wp-content directory of your WordPress installation:

sudo mv object-cache.php /var/www/html/wp-content/

Depending on your WordPress installation, your location may be different.

Step 4 — Enable Cache Settings in wp-config.php

Next, edit the wp-config.php file to add a cache key salt with the name of your site (or any string you would like).

nano /var/www/html/wp-config.php

Add this line at the end of the * Authentication Unique Keys and Salts. section:

define('WP_CACHE_KEY_SALT', 'example.com');

You can use your domain name or another string as the salt.

Note: For users hosting more than one WordPress site, each site can share the same Redis installation as long as it has its own unique cache key salt.

Also, add the following line after the WP_CACHE_KEY_SALT line to create a persistent cache with the Redis object cache plugin:

define('WP_CACHE', true);

All together, your file should look like this:

 * Authentication Unique Keys and Salts.
 
. . .
 
define('NONCE_SALT',       'put your unique phrase here');

define('WP_CACHE_KEY_SALT', 'example.com');
define('WP_CACHE', true);

Save and close the file.

Step 5 — Restart Redis and Apache

Finally, restart redis-service and apache2.

Restart Redis:

sudo service redis-server restart

Restart Apache:

sudo service apache2 restart

Restart php5-fpm if you are using it; this is not part of the basic installation on DigitalOcean:

sudo service php5-fpm restart 

That’s it! Your WordPress site is now using Redis caching. If you check your page load speeds and resource use, you should notice improvements.

Monitor Redis with redis-cli

To monitor Redis, use the redis-cli command like so:

redis-cli monitor

When you run this command, you will see the real-time output of Redis serving cached queries. If you don’t see anything, visit your website and reload a page.

Below is example output from a WordPress site configured per this guide using Redis:

OK
1412273195.815838 "monitor"
1412273198.428472 "EXISTS" "example.comwp_:default:is_blog_installed"
1412273198.428650 "GET" "example.comwp_:default:is_blog_installed"
1412273198.432252 "EXISTS" "example.comwp_:options:notoptions"
1412273198.432443 "GET" "example.comwp_:options:notoptions"
1412273198.432626 "EXISTS" "example.comwp_:options:alloptions"
1412273198.432799 "GET" "example.comwp_:options:alloptions"
1412273198.433572 "EXISTS" "example.comwp_site-options:0:notoptions"
1412273198.433729 "EXISTS" "example.comwp_:options:notoptions"
1412273198.433876 "GET" "example.comwp_:options:notoptions"
1412273198.434018 "EXISTS" "example.comwp_:options:alloptions"
1412273198.434161 "GET" "example.comwp_:options:alloptions"
1412273198.434745 "EXISTS" "example.comwp_:options:notoptions"
1412273198.434921 "GET" "example.comwp_:options:notoptions"
1412273198.435058 "EXISTS" "example.comwp_:options:alloptions"
1412273198.435193 "GET" "example.comwp_:options:alloptions"
1412273198.435737 "EXISTS" "example.comwp_:options:notoptions"
1412273198.435885 "GET" "example.comwp_:options:notoptions"
1412273198.436022 "EXISTS" "example.comwp_:options:alloptions"
1412273198.436157 "GET" "example.comwp_:options:alloptions"
1412273198.438298 "EXISTS" "example.comwp_:options:notoptions"
1412273198.438418 "GET" "example.comwp_:options:notoptions"
1412273198.438598 "EXISTS" "example.comwp_:options:alloptions"
1412273198.438700 "GET" "example.comwp_:options:alloptions"
1412273198.439449 "EXISTS" "example.comwp_:options:notoptions"
1412273198.439560 "GET" "example.comwp_:options:notoptions"
1412273198.439746 "EXISTS" "example.comwp_:options:alloptions"
1412273198.439844 "GET" "example.comwp_:options:alloptions"
1412273198.440764 "EXISTS" "example.comwp_:options:notoptions"
1412273198.440868 "GET" "example.comwp_:options:notoptions"
1412273198.441035 "EXISTS" "example.comwp_:options:alloptions"
1412273198.441149 "GET" "example.comwp_:options:alloptions"
1412273198.441813 "EXISTS" "example.comwp_:options:notoptions"
1412273198.441913 "GET" "example.comwp_:options:notoptions"
1412273198.442023 "EXISTS" "example.comwp_:options:alloptions"
1412273198.442121 "GET" "example.comwp_:options:alloptions"
1412273198.442652 "EXISTS" "example.comwp_:options:notoptions"
1412273198.442773 "GET" "example.comwp_:options:notoptions"
1412273198.442874 "EXISTS" "example.comwp_:options:alloptions"
1412273198.442974 "GET" "example.comwp_:options:alloptions"

Press CTRL-C to stop the output.

This is useful for seeing exactly what queries Redis is processing.

Conclusion

After following this guide, WordPress will now be configured to use Redis as a cache on Ubuntu 14.04.

Below are some additional security and administration guides for WordPress that may be of interest:

How To Configure Secure Updates and Installations in WordPress on Ubuntu

How To Use WPScan to Test for Vulnerable Plugins and Themes in Wordpress

How To Use WP-CLI to Manage your WordPress Site from the Command Line

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Sharon Campbell
Sharon Campbell
Editor
See author profile

Current fan and former Editorial Manager at DigitalOcean. Hi! Expertise in areas including Ubuntu, Docker, Rails, and more.

Still looking for an answer?

Was this helpful?
Leave a comment...

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Awesome article! First redis-wordpress tutorial that actually worked properly for me.

UPDATE: For some weird reason, it slowed down my website??? Derp.

Does it work with Nginx and Php-FPM out of the box?

I have APC installed, I think I have to uninstall it first, right?

Works like a sharm!

@smithmconnor Redis actually slowed down my website as well. Using Upstart theme (from WooThemes) - now all pages take at least 10 seconds to load, and sometimes don’t load at all. Now after I reboot the server I keep forgetting to stop the redis service - does anyone know how to uninstall redis? Regis seems to work ok on other, perhaps more simple, Wordpress themes. Thanks

If you are seeing any odd slowdowns, I would advise to disable any other caching, such as php-apc or memcached.

This comment has been deleted

I have followed this tutorial, but dont get it to work. When i put object-cache.php in this tutorial, and access the wordpress site - it gives me a blank page with error returning that it could not find “redis”. Redis is up n running, works fine and cache other sites without a problem. But with object-cache.php in wp-content folder on wordpress sites, it just give me blank page and error on line 300-something, could not find redis.

Any idea? Or any other that has this problem?

Fatal error: Class ‘Redis’ not found in /path/to/script/ on line 305

Are there any benchmarks or performance measurements? When did redis is better than other caching options?

I installed it and it works, but it really slow down the complete wordpress website instead of speeding up …

http://www.jeedo.net/lightning-fast-wordpress-with-nginx-redis/

This works MUCH FASTER - like a rocket on my wordpress installation.

Replying to info724961

This comment has been deleted

This slowed down my site too. Using Ubuntu 14.04 with nginx and php5-fpm. Any ideas?.

As for my Wordpress installation (Centos + nginx + php-fpm + opcache). It seems the best performance I get with mysql cache tuning (query_cache_size=64M, query_cache_min_res_unit=1024). Redis unfortunately only slows this configuration.

This doesn’t seem to work for me.

Per your instructions you mention to add,

define('WP_CACHE', true);

However, doing that then enables this in wp-settings:

if ( WP_CACHE )
	WP_DEBUG ? include( WP_CONTENT_DIR . '/advanced-cache.php' ) : @include( WP_CONTENT_DIR . '/advanced-cache.php' );

That is it looks for /advanced-cache.php which of course doesn’t exist. As the instructions above mention to add a file called object-cache.php. Should the file you mention in this post actually be called, “advanced-cache.php” otherwise what should we do about wordpress needing that file if we enable wp_cache = true.

Scott, those lines are from wp-settings.php (line 65) and as such are indeed part of a stock WordPress install. This is from the WordPress Codex:

The WP_CACHE setting, if true, includes the wp-content/advanced-cache.php script, when executing wp-settings.php.

So, as Chris has pointed out, if there’s no advanced-cache.php script, there’s not much point setting the define.

slows down my Wordpress-Blogs:

Finished 1000 requests


Server Software:        nginx/1.8.0
Server Hostname:        my.tld
Server Port:            80

Document Path:          /
Document Length:        10941 bytes

Concurrency Level:      25
Time taken for tests:   20.338 seconds
Complete requests:      1000
Failed requests:        0
Total transferred:      11174000 bytes
HTML transferred:       10941000 bytes
Requests per second:    49.17 [#/sec] (mean)
Time per request:       508.458 [ms] (mean)
Time per request:       20.338 [ms] (mean, across all concurrent requests)
Transfer rate:          536.53 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:       17   19   8.2     18     183
Processing:   264  483  91.5    462    1198
Waiting:      260  472  89.4    452    1188
Total:        332  502  91.6    481    1221

Percentage of the requests served within a certain time (ms)
  50%    481
  66%    502
  75%    516
  80%    531
  90%    572
  95%    631
  98%    787
  99%   1003
 100%   1221 (longest request)
Finished 1000 requests


Server Software:        nginx/1.8.0
Server Hostname:        my.tld
Server Port:            80

Document Path:          /
Document Length:        15295 bytes

Concurrency Level:      25
Time taken for tests:   73.570 seconds
Complete requests:      1000
Failed requests:        0
Total transferred:      15472000 bytes
HTML transferred:       15295000 bytes
Requests per second:    13.59 [#/sec] (mean)
Time per request:       1839.244 [ms] (mean)
Time per request:       73.570 [ms] (mean, across all concurrent requests)
Transfer rate:          205.37 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:       17   18   3.7     18      86
Processing:   352 1802 259.0   1796    2466
Waiting:      333 1752 254.0   1747    2398
Total:        371 1820 259.1   1814    2491

After installing this wp-config is calling wp-setting advanced-cache.php. not sure if this is a correct setup to run redis for wordpress.

Slowed down my wp site (512mb) by more than 200% Disabled all other server caching options as recommended - reboot - filled cache - no change

P.S.: we need a “thumbs down” button so other people know beforehand that this doesn’t work for “many people”

Great Article. There are a lot of reasons it could slow down a site. The first step is to see what is happening during the slow down. It is most likely a memory shortage that is causing swapping. Try reducing the memory footprint demands. Try running top in an ssh window and seeing if there is a memory shortfall. You could also tune the swap requirements. But the topic of server optimization is so broad, there is no way to cover it in a simple comment. The simplest and quickest test would be to spin up a new server with **more memory ** using a snapshot or backup image of the target server. Leaving it up for a few hours would only cost a few cents, and save you hours of server tuning.

I have had a bad experience with Redis and still find memcached a great tool. It will take time for me to make that change to redis since it cause a huge delay in latency for my dns. Caching was Amazing, just to long to pull my domain.

My Setup Now Nginx, HHVM w/ PHP5 FPM, Varnish, Memcached, Monit. Used the Ansible Mercury playbook for my wordpress

Site Speedtest

Did a decent job.

The benchmark is wildly misleading, so don’t be surprised if you install this and it “doesnt work”. You would typically get no speed increase.

I have spoken about why in this presentation: http://snippets.khromov.se/presentation-the-wordpress-object-cache/

The highlights are (slide 31):

  • Object Cache works almost exclusively at the database layer
  • Content still has to be formatted / rendered
  • All filters still run
  • MySQL server has similar response time to caching backends under low load

The last point is key. If your DB server performance is bad, persistent Object Cache may help, but when it’s on the same machine as your web server, they share the same resources so this doesn’t apply, hence installing persistent object cache on a single-server environment is largely futile and may actually decrease performance.

This slowed down my site too. Using Ubuntu 14.04 with nginx and php5-fpm. Any ideas?.

As for my Wordpress installation (Centos + nginx + php-fpm + opcache). It seems the best performance I get with mysql cache tuning (query_cache_size=64M, query_cache_min_res_unit=1024). Redis unfortunately only slows this configuration.

This doesn’t seem to work for me.

Per your instructions you mention to add,

define('WP_CACHE', true);

However, doing that then enables this in wp-settings:

if ( WP_CACHE )
	WP_DEBUG ? include( WP_CONTENT_DIR . '/advanced-cache.php' ) : @include( WP_CONTENT_DIR . '/advanced-cache.php' );

That is it looks for /advanced-cache.php which of course doesn’t exist. As the instructions above mention to add a file called object-cache.php. Should the file you mention in this post actually be called, “advanced-cache.php” otherwise what should we do about wordpress needing that file if we enable wp_cache = true.

Scott, those lines are from wp-settings.php (line 65) and as such are indeed part of a stock WordPress install. This is from the WordPress Codex:

The WP_CACHE setting, if true, includes the wp-content/advanced-cache.php script, when executing wp-settings.php.

So, as Chris has pointed out, if there’s no advanced-cache.php script, there’s not much point setting the define.

slows down my Wordpress-Blogs:

Finished 1000 requests


Server Software:        nginx/1.8.0
Server Hostname:        my.tld
Server Port:            80

Document Path:          /
Document Length:        10941 bytes

Concurrency Level:      25
Time taken for tests:   20.338 seconds
Complete requests:      1000
Failed requests:        0
Total transferred:      11174000 bytes
HTML transferred:       10941000 bytes
Requests per second:    49.17 [#/sec] (mean)
Time per request:       508.458 [ms] (mean)
Time per request:       20.338 [ms] (mean, across all concurrent requests)
Transfer rate:          536.53 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:       17   19   8.2     18     183
Processing:   264  483  91.5    462    1198
Waiting:      260  472  89.4    452    1188
Total:        332  502  91.6    481    1221

Percentage of the requests served within a certain time (ms)
  50%    481
  66%    502
  75%    516
  80%    531
  90%    572
  95%    631
  98%    787
  99%   1003
 100%   1221 (longest request)
Finished 1000 requests


Server Software:        nginx/1.8.0
Server Hostname:        my.tld
Server Port:            80

Document Path:          /
Document Length:        15295 bytes

Concurrency Level:      25
Time taken for tests:   73.570 seconds
Complete requests:      1000
Failed requests:        0
Total transferred:      15472000 bytes
HTML transferred:       15295000 bytes
Requests per second:    13.59 [#/sec] (mean)
Time per request:       1839.244 [ms] (mean)
Time per request:       73.570 [ms] (mean, across all concurrent requests)
Transfer rate:          205.37 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:       17   18   3.7     18      86
Processing:   352 1802 259.0   1796    2466
Waiting:      333 1752 254.0   1747    2398
Total:        371 1820 259.1   1814    2491

After installing this wp-config is calling wp-setting advanced-cache.php. not sure if this is a correct setup to run redis for wordpress.

Slowed down my wp site (512mb) by more than 200% Disabled all other server caching options as recommended - reboot - filled cache - no change

P.S.: we need a “thumbs down” button so other people know beforehand that this doesn’t work for “many people”

Great Article. There are a lot of reasons it could slow down a site. The first step is to see what is happening during the slow down. It is most likely a memory shortage that is causing swapping. Try reducing the memory footprint demands. Try running top in an ssh window and seeing if there is a memory shortfall. You could also tune the swap requirements. But the topic of server optimization is so broad, there is no way to cover it in a simple comment. The simplest and quickest test would be to spin up a new server with **more memory ** using a snapshot or backup image of the target server. Leaving it up for a few hours would only cost a few cents, and save you hours of server tuning.

I have had a bad experience with Redis and still find memcached a great tool. It will take time for me to make that change to redis since it cause a huge delay in latency for my dns. Caching was Amazing, just to long to pull my domain.

My Setup Now Nginx, HHVM w/ PHP5 FPM, Varnish, Memcached, Monit. Used the Ansible Mercury playbook for my wordpress

Site Speedtest

Did a decent job.

The benchmark is wildly misleading, so don’t be surprised if you install this and it “doesnt work”. You would typically get no speed increase.

I have spoken about why in this presentation: http://snippets.khromov.se/presentation-the-wordpress-object-cache/

The highlights are (slide 31):

  • Object Cache works almost exclusively at the database layer
  • Content still has to be formatted / rendered
  • All filters still run
  • MySQL server has similar response time to caching backends under low load

The last point is key. If your DB server performance is bad, persistent Object Cache may help, but when it’s on the same machine as your web server, they share the same resources so this doesn’t apply, hence installing persistent object cache on a single-server environment is largely futile and may actually decrease performance.

Hello, I’m currently have this setup ( ubuntu 14.04, nginx, php-fpm, hhvm and mariaDB) after following this tutorial to install redis, my site load decrease like 300% ! what could it be ?

All my photos which have special characters (Chinese, French) in their name are not showing after this tutorial (and the other one with FastCGI cache). Is it about character-set? I’ve added ‘charset UTF-8;’ in nginx.conf and restarted nginx, still not working. How to fix this?

here is an example of broken links: http://lineday.co/mur-des-je-taime-paris/

While this sounds nice in principle, just use a plugin like WP Fastest Cache. It speeds up the websites big time. Redis will actually slow down sites if not properly configured.

The object-cache.php file from this tutorial slowed down my site very much. Use this object-cache.php file instead for super quick load times! WP Redis

After installing the plugin;

  1. Move the object-cache.php from the plugins’ directory to wp-content
  2. Add $redis_server = array( 'host' => '127.0.0.1', 'port' => 6379); to wp-config.php, along with the “defines” from this tutorial. (WP_CACHE_KEY_SALT and WP_CACHE)
  3. Restart PHP/HHVM, Apache/NGINX and Redis Server
  4. UP UP AND AWAAAY!

Using this live here: https://sverige.science/

I’m getting DOMContentLoaded in approx 500ms now! :)

This comment has been deleted

There are many advance caching systems available that can be used to speed up WordPress. Redis has a caching mechanism that can be used to speed up object cache of WordPress thus improving database queries. Above Setup is pre configure in Cloudways platform. DigitalOcean Servers are integrated in Cloudways. Integrating it with DigitalOcean WordPress is easy, follow this tutorial for a quick guide: Redis Cache with WordPress

Hi. Nice post but where i must include the Redis-DB Password for more security?

I’ve got this up and running on my site and everything seems much faster. However, I’m wondering what’s the difference between implementing Redis this way, and Jim Westergreen’s method, which uses a script for index-with-redis and Predis:

https://www.jimwestergren.com/wordpress-with-redis-as-a-frontend-cache/

Is one better than the other? Can both be used at the same time? Westergreen claims he uses no caching plugins, which would be great (I’ve got w3tc set up pretty well, but…it has its issues).

I’m also wondering, will this method cause issues with shopping carts, FB like counters, and such?

Thanks!

Also, add the following line after the WP_CACHE_KEY_SALT line to create a persistent cache > with the Redis object cache plugin: define('WP_CACHE', true);

WP_CACHE is for PAGE CACHING ONLY

Switching it on , results in a warning that wordpress can not find the relative cache plugin.

Installation Done perfectly,But after adding into wp-config.php im getting 505 error…Looking at error_log shows the below :

[11-May-2017 10:43:18 UTC] PHP Fatal error: Class ‘Redis’ not found in /home/acctname/public_html/wp-content/object-cache.php on line 332

Please how to fix this ?

Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.
Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.