Make a Cache Warmer to Speed up Drupal on a VPS

So you’ve gone to a lot of trouble to cache & optimize all aspects of your Drupal web site, but you still find it loading slowly when nobody’s visited it in a while? You probably need to disable Drupal’s built-in cron and set up a cache warmer.  

The problem is, in most circumstances Drupal’s built-in cron will empty the site’s cache. So you need to then go through and visit each page to load the pages back into cache.

To automate this, first turn off Drupal’s built-in cron by going to admin/config/system/cron in Drupal and set “run cron every” to “never.”

Then create an XML sitemap for your site. (The XML Sitemap module does a nice job of automating this for you.)

Now, on your VPS create a new text file (called something like “croncache.sh”) containing this:

#!/bin/bash
#
# First, run cron, which may flush the page cache:
/usr/bin/php /home/yourdomain/www/cron.php cron_key=(long-string-of-gibberish) >/dev/null
#
# Now, use the sitemap to reload page cache, 1 page every 0.6s to reduce load:
/usr/local/bin/wget --quiet https://www.yourdomain.com/sitemap.xml --output-document - | egrep -o "https://www.yourdomain.com[^<]+" | /usr/local/bin/wget -q --delete-after -i - --wait 0.6

That will first run cron using the external URL that you can find on your site at: admin/reports/status, and then it’ll hit every page on your sitemap to get them all back into cache.

Now edit cron on your VPS to run this script every two hours or so. (Remember to check permissions and make it executable (using chmod or a file manager’s GUI)  if it won’t run.)

Steve