Fast random post in WordPress (with Apache’s help)

In this tutorial, I’m going to walk through how to use mod_rewrite‘s RewriteMap directive to redirect to a random WordPress post any time a visitor visits a specific URL, in this case /random. This technique is very fast, requires no PHP overhead beyond that which is normally needed to serve pages from WordPress, so it should be compatible with any caching methods being employed within WordPress. If you are using an upstream cache, like Varnish, you’ll need to exclude the URL you set up in the rewrite.


There’s a few parts to this method:

  • Getting the list of post permalinks out of WordPress, and re-formatting them into a format that Apache can use.
  • Scheduling the generation of the file that Apache’s RewriteMap directive will use.
  • Configuring Apache’s RewriteMap and RewriteRule.

Extracting the URLs from WordPress

The first step is to get the URLs out of WordPress and formatted into a format Apache can use. I wrote a small PHP script to do this. The script is dropped into the WordPress install directory, and is protected from being called directly.

The script is pretty simple – it just gets all the posts (the default arguments to get_posts already filters it to only published posts) and puts their URLs into an array. Then it joins the array with pipes, and outputs it to stdout. The output of this file should be piped to the file that RewriteMap directive will use. The next step will do this.

Scheduling the generation of the RewriteMap file

Next, we need to schedule the generation of this file. I recommend using cron.

0 0 * * * cd /var/www/blog; /usr/bin/php rewritemap-generator.php > /var/www/wordpress-rewritemap.txt

A few assumptions – change these to accomodate your setup:

  • The script is in the WordPress directory and named rewritemap-generator.php.
  • The WordPress blog is installed in /var/www/blog.
  • The output file will be in Apache’s home directory, /var/www and will be called wordpress-rewritemap.txt. The filename can be anything, and can have any extension.
  • PHP CLI is available, and installed at /usr/bin/php.
  • The cron job will be set to run once per day.

Configuring Apache

Almost done. We need to set up Apache to read the map file and perform the rewriting. In your VirtualHost section of your configuration file, add the following:

RewriteEngine   On
RewriteMap      posts   rnd:/var/www/wordpress-rewritemap.txt
RewriteRule     ^random/?$  ${posts:posts} [R,L]

Finally, reload Apache’s configuration or restart the service.


Open up a browser tab, and browse to your WordPress blog’s home page. Now, add random after the URL, and you’ll be redirected to a random post, all with no additional overhead to PHP.

Test it on this site! Click here. (Will load in new tab).

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.