Writing complex mod_rewrite
redirection rules with .htacess
can lead to a downwards spiral of frustration, paranoia and utter bewilderment.
Today I’m working on a particularly tricky scenario so I decided to get more methodical about it.
Here’s a summary of the workflow I’ve been using. I have to remind myself to be deliberately slow and methodical – if I get impatient and rush ahead I’m much more likely to miss something unexpected and end up going in circles.
My setup uses a locally installed Apache server and the Firefox Selenium IDE plugin:
- Make a new directory in the server root, to keep everything in one place, with an
index.php
echoing some debugging info:
- Break the task up into a list of manageable blocks e.g.
- Set a cookie
- Append flag to URL if cookie is present
- If flag present remove it and set query string
- Make directories named after each block e.g.
/set-a-cookie
/append-flag-to-url-if-cookie-is-present
/if-flag-present-remove-it-and-set-query-string
- Each directory contains an
.htaccess
file andindex.php
- Put a comment at the top of each
.htaccess
identifying the block it addresses e.g.# set-a-cookie
. That way when you start copying & pasting you can keep track of what each block does - The index file simply pulls in the root
index.php
:
- Make a new Selenium test suite and begin constructing a test case for the first block. These tests are generally pretty simple: open a URL and check that the location is redirected as expected.
- Remember to test for multiple scenarios such as requests for:
- with trailing slashes
- without trailing slashes
- with query strings
index.php
- static files
- Start working on the
.htaccess
file, running the tests each time you make a change. Once a block is working move to the next one - Repeat until done
Work slowly and try not to make too many changes at once. mod_rewrite
may seem like voodoo but don’t let it give you the heebie-jeebies!