How to ModRewrite

Discussion in 'Programming' started by db_man, Jun 5, 2007.

  1. #1
    If you are anything like me, the very sight of mod_rewrite code makes your brain cramp.

    In all honesty, it looks like complete and utter gibberish, but there is a logic underneath it all.

    You may already know that it can take your cumbersome dynamic URLs and magically transform them into understandable language instead of incomprehensible gibberish.

    Par Example: (that means ‘for example’. It’s French. Really.)

    ORIGINAL URL:
    http://myawesomesite.com/index.php?tag=tutorial&page=2

    MOD_REWRITE URL:
    http://myawesomesite.com/tutorial/2

    These URLs are better for a couple reasons.
    Primarily, they are easier for your visitors to understand and remember.
    Beyond that, these URLs can be keyword rich, which is great for search engines!

    So now you see, mod_rewrite is a powerful tool if one can wrangle the language and make it work!

    Example Deux (…..you get it)

    Alright, so you’ll need to goto whatever folder of your site you are wanting to start rewriting URLs from.

    Backup the .htaccess file (just in case) and then pop ‘er open!
    For those of you just beginning to read up on this stuff, an .htaccess file is an Apache server based configuration file the lets you make changes to the way your server….uhhh…serves……essentially.For more information than that last meager explanation can provide, check out the official guide:
    apache.org



    Now then,

    You got your .htaccess file open? Good.
    Lets use the URL from the previous example.

    Say this is your site:

    http://myawesomesite.com/index.php?tag=tutorial&page=2

    And, never being one to shy away from a challenge, you decide that you want URLs like this:

    http://myawesomesite.com/tutorial/2

    “Impossible?” You ask?

    “NO!” I say!

    To accomplish this amazing feat of URL trickery, add the following lines to your .htaccess file.

    RewriteEngine On
    RewriteRule tutorial/2 index.php?tag=tutorial&page=2

    To understand this, lets break it down line by line:

    RewriteEngine on:
    This line does exactly what it says, it turns on the engine that lets your Rewrite URLs

    On line two, we see:
    RewriteRule: This line tells the server to expect you to specify a rule about rewrite the url
    tutorial/2: This line tells the server that when it serves the dynamic URL specific on the next line, it should replace it with this clean static URL
    index.php?tag=tutorial&page=2: This tells the server which dynamic address to look out for.

    BAM!

    You’ve just learned to rewrite a URL……of course, its not a very efficient way to rewrite URLs for large sites, is it? Better start practicing if you want to achieve more!
     
    db_man, Jun 5, 2007 IP