mod_rewrite and Short Urls - What you really want to know.

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.

Solution 1

File: .htaccess

1
2
3
4
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+) /index.php [L]

File: index.php

1
2
3
$urlArray = explode("/",$_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.

Solution 1.a (more elegant)

File: .htaccess

1
2
3
4
5
6
7
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

That version just checks to make sure the module is installed.

Solution 2

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

File: .htaccess

1
2
3
RewriteEngine on
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: Condtion, If the file we’re requesting is not a file…

  • RewriteCond %{REQUEST_FILENAME} !-d
    Read this as: Condtion, If the file we’re requesting is not a directory…

  • RewriteRule . /index.php [L]
    Then Rewrite this url to index.php ([L] forces it to be the last redirect)