I recently opened up an old .htaccess and I was struck with the memory of how much it sucked trying to Google search for some real, working, answers on making short urls.

So here you go, my quick tip on what you really want to know about mod_rewrite.

If you want an actual explanation of what is going on here it’s at the bottom.

Rewrite Conditions

# File: .htaccess
# File Location: /
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+) /index.php [L]
// File: index.php
// File Location: /

$urlArray = $_SERVER['REQUEST_URI']);
array_shift($urlArray); // Gets rid of the blank first param.

Now you have an array with all of your parts, and you can map them accordingly.

Quick Hack

If you have just a couple of pages that you want to look prettier:

# File: .htaccess
# File location: /

RewriteEngine on

# Start rewriting your urls
RewriteRule ^home$ index.php
RewriteRule ^about$ about.php

And you just keep adding RewriteRule’s for each page. This is really only helpful when you just have a set of static looking pages for a site.

Explanation

  • RewriteEngine on
    • Tells Apache to turn on the RewriteEngine for this folder
  • RewriteCond %{REQUEST_FILENAME} !-f
    • Read this as: We’ll rewrite the URL if the requested file can’t be found
  • RewriteCond %{REQUEST_FILENAME} !-d
    • Read this as: We’ll rewrite the URL if the directory can’t be found
  • RewriteRule . /index.php [L]
    • Then Rewrite this url to index.php, and make it the last redirect