Custom Wordpress rewrites

Wordpress is a wonderful blogging/CMS software. One of the great things about it is, that it creates nice search engine friendly URLs for you automatically. This is accomplished by redirecting all the page requests to Wordpress, that does some rewrite magic on the PHP side.

Posted by Sami Tikka on December 23, 2007

Wordpress is a wonderful blogging/CMS software. One of the great things about it is, that it creates nice search engine friendly URLs for you automatically. This is accomplished by redirecting all the page requests to Wordpress, that does some rewrite magic on the PHP side.

Let's say you have created a WP plugin, that extends WP functionality with some special page (which I won't go into here now). You use WP hooks to integrate the pages into normal WP template construction routine, and monitor request URI for GET variables. Now, suppose you also want to have a nice clean search engine friendly URL for your special page.

So, you are monitoring for page requests like this coming in:

http://www.yourwpsite.com/?special=somevariable

And you would like your user to be able to access the same functionality like this:

http://www.yourwpsite.com/special/somevariable

Let's set up a rewrite of our own. In your WP top level folder is a .htaccess file and there's a rewrite rule created by WP:

RewriteRule . index.php [L]

Change that to this:

RewriteRule !^special /index.php [L]
RewriteRule ^special(\/?)([^/.]*)/?$ /?special=$2 [C]

Let's go through what is going on here. The first rule is saying:

"If user is not (!) requesting our special page, rewrite the request to index.php as normal and don't process any more rewriterules ([L])."

Now, the request for the special page doesn't pass the first test, and goes on to the second rule, which says:

"If the requested page starts (^) with "special", is possibly followed by "/" ((\/?)) and some query string that doesn't include "/" (([^/.]*)) and possibly ends with "/" (/?$), rewrite URL to "/?special=querystring" AND continue executing rewrite rules ([C])."

Now, it loops back to beginning to search for more rewrites, and finds the first rule, which now matches, and the request URL is rewritten to /index.php with all the GET parameters still intact for your plugin hooks to process.

That's all for now.