Einar Egilsson

Pretty WordPress Permalinks on IIS

Posted: Last updated:

UPDATE 16.09.2009: I don't update this script anymore, it might not work on newer versions of WordPress. An updated, more robust solution can be found at http://www.ikailo.com/94/url-modrewrite-workaround-iis-60/, go there if the solution below causes problems for your site.

I've been searching the web a bit for a way to make pretty permalinks work correctly on this site. The site is hosted on IIS so using mod_rewrite won't work, and it's on a shared server so the option of installing a mod_rewrite alternative for IIS won't work either. I could get away with having almost pretty urls, with a index.php in them, like this: http://einaregilsson.com/index.php/2007/07/30/pretty-wordpress-permalinks-on-iis/ but I didn't like it.

The Using Permalinks section on the WordPress page has a lot of info on this and it links to one solution that uses custom 404 pages to make this work but unfortunately I don't think it's a very good solution at all. What it does is parse the url from the 404 string, then re-implement all the rewrite url matching itself, make its own http request to the correct url, then write the data from that request into the response. It's a good effort but it's duplicating functionality already in WordPress and making a new http request for every page hit which I don't like. After searching around some more I found another 404 page solution that is very simple and elegant. All you have to do is create a 404 page and put the following 4 lines in it:

<?php $qs = $_SERVER['QUERY_STRING']; $pos = strrpos($qs, '://'); $pos = strpos($qs, '/', $pos + 4); $_SERVER['REQUEST_URI'] = substr($qs, $pos); $_SERVER['PATH_INFO'] = $_SERVER['REQUEST_URI']; include('index.php'); ?>

All this does is fix the REQUEST_URI and PATH_INFO variables and then include index.php, so WordPress will do the rest. It's simple, it doesn't duplicate functionality already in WordPress and it doesn't have the overhead of another http request for every page hit. The installation steps are:

  1. Create the file wp-404-handler.php in your base WordPress folder. (you can also download it here).
  2. Set your sites 404 page to point to the wp-404-handler.php url. Most control panels at web hosts allow you to do this. If you've got the option to select between FILE and URL then choose URL.
  3. Go to Options -> Permalinks in your WordPress admin page, and choose an appropriate structure for your links. I chose Custom with this pattern: /%year%/%monthnum%/%day%/%postname%/
  4. Enjoy!

If you read this far you should probably follow me on Twitter or check out my other blog posts. I no longer have comments on this blog, but you can send me an email if you have some comments about this page.