Lessons Learned: Dynamic Urls to Static with Mod Rewrite

It’s a good thing that I have Caleb’s photo on my desktop and Chesney’s photo sitting on top of my montior because they reminded me that I have something to live for. After hours of staring at Perl regular expressions, I came very close to putting my head through my monitor.

If this makes perfect sense to you…

RewriteRule ^/?([^/.]*)/?([^/.]*)/?$ index.php?var1=$1&var2=$2 [L]

…then you are a geek. This is a rewrite rule using dreaded mumbo-jumbo called Perl regular expressions.

This all started when I started looking at timches.com’s stats and finding that I wasn’t getting as many hits after the redesign. I found the culprit to be the new dynamic pages. Apparently, search engine robots don’t like GET variables found in urls like:

http://www.timches.com/pictures/show_album.php?id=196

I used rewrite rules in .htaccess files to create an alternative “static” link:

http://www.timches.com/pictures/2005/05/196/happy_1st_birth.html

Following the example of popular CMS packages like WordPress and Movable Type, I included the title within the last part of the url, which helps get a higher listing on search engines, so I’m told.

The rewrite rule to make that static link happen is just one line:

RewriteRule ^([0-9]*)/([0-9]*)/([0-9]*)/([a-zA-Z0-9_]*).html show_album.php?id=$3&y=$1 [L]

Here’s several sites that I found helpful in learning how to do this (and for my future reference as well).

So now I sit and watch to see if indeed this helps my search engine rankings. If it doesn’t, well, that’s why I have Caleb and Chesney’s pictures close to my monitor.

Related Posts

Comment via Facebook

No Comments

  1. Phil

    Regex’s are really useful, but I agree they are a headache.

    I noticed my archives don’t even get spidered…. I really need to do something about that. mod_rewrite should do the trick.

    One
    nifty thing I have is a custom 404 page that redirects bad pages to a
    blog search for the term that was not found. For instance:

    http://philisha.net/apache redirects to a search of my entire blog for the term ‘apache’. It is pretty nifty.

  2. Phil

    Here’s the code if you’re curious.

    <?php
    $search_term = preg_replace(“#/$#”,”",$_SERVER['REQUEST_URI']);
    ereg(“([^\/]*)$”, $search_term, $regs);
    $search_term = $regs[1];
    $search_url = ‘index.php?criteria=’;
    $full_search_url = $search_url . $search_term;

    header(“HTTP/1.1 301 Moved Permanently”);

    header(“Location: $full_search_url”);

    header(“Connection: close”);
    ?>

  3. Tim

    That’s a good idea–I don’t have a search on this subdomain, but on
    my main timches.com, I’d like to maybe just bring up a list of results
    on that last term that doesn’t exist…

    I do like the custom error 404 page that I made though.

    And my custom error 403 page too.

Thoughts? Comments?