Rewrite/redirect from one dynamic page to another.

URL rewriting always stumps me. I never remember the details and have to rely on search or looking at old .htaccess files I’ve done before to get what I need for a new project. I’m not sure it’ll ever be something I’ll “master” (in that I can write the code and not need to search for examples).

ANYWAY, the last time I was stumped was where I needed to redirect requests from /faculty/bio.php?id=45 to /people/bio.php?id=45. Seems simple enough. The problem is that regular redirects don’t work for items in the query string so something like this won’t work:

Redirect /faculty/bio.php?id=45 http://site.com/people/bio.php?id=45

Instead I needed to use a Rewrite instead of a Redirect which are far more complicated. I found a few great resources but I couldn’t get it to work. I decided that instead copy/paste I would type out what I read so that maybe I could master the syntax.

Anyway, here is what I came up with:

RewriteCond %{QUERY_STRING} ^id=([0-9]*)$
RewriteRule ^faculty/bio.php$ /people/bio.php?id=$1 [R=301,L]

Long story short that was ALL WRONG. Because of one reason. The problem was that I kept using $1 instead of %1. $1 is matches on the first RewiteRule pattern (of which I didn’t have any) and %1 matches to the first RewriteCond pattern (the pattern in parentheses or course).

Another problem was I kept trying this:

RewriteRule ^/faculty/bio.php$ /people/bio.php?id=$1 [R=301,L]

The problem with that rule is the slash at the beginning of the url match (plus the $1 instead of %1 . . . it’s always compounding errors that take the longest to fix). The “match” in the rule always starts from the current folder and you can’t tell it to start at the root from some other folder (which makes sense . . . imagine I had a /stuff folder and it it was some redirect rule that matched on /faculty . . . that would NEVER match since you are already in the /stuff folder).

Anyway, a few tough lessons I’ll probably forget soon. Maybe writing it out here will help with my memory issues.

Sheldon