Apache Mod Rewrite

One if the cleanest ways to setup a site is to use mod_rewrite in Apache. I am going to show you a simple way to do this using an htaccess file and a little PHP. First step is to make an htaccess file with the following code:

RewriteEngine on
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ index.php?loc=$1

Now everything that is not a folder or a file will get passed to the index.php file as $_GET['loc']. You could change the index.php to any file you like and the ?loc= to some other variable if you like.

Next you need to groom the url. Do not leave out this step. You are injecting the url into your script... I suggest something solid like the following:

PHP:
  1. <?php
  2. $url = preg_replace('/[^[:alnum:]\-\/]/', '', $_GET['loc']);
  3. ?>

So now you have the url into your script safely so you need to break it apart. You are basically going to pass variables here. All you have to do is explode on the forward slash. You can do it simply like this:

PHP:
  1. <?php
  2. $parts = explode('/',$url);
  3. $section = $parts[0];
  4. $subsection = $parts[1];
  5. ?>

These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Netvouz
  • DZone
  • Reddit
  • Furl
  • NewsVine
  • Simpy
  • Slashdot
  • Spurl
  • StumbleUpon
  • YahooMyWeb
  • TailRank

Home | Apache | Apache Mod Rewrite