Friendly URLs (revisited)

Turn dynamic URLs into friendly URLs

I’m sure we’re all familiar with URLs that look like this:

http://www.example.com/?nav=page

These type of URLs aren’t particularly “friendly”, inf act they are so ugly that even Google doesn’t like them!

Google suggests that search engines do not like dynamic URLs as much as static URLs.

“static” or “friendly” versions of the above URL could be as follows:

http://www.example.com/page.html

Apache’s mod_rewrite can be easily used via a file called “.htaccess” to turn dynamic urls into friendly urls.

Here is an example of how it’s done:

#Turn on the Rewrite Engine
RewriteEngine on
#Set the base path
RewriteBase /
#Check that the lookup isn’t an existing file
RewriteCond %{REQUEST_FILENAME} !-f
#Check that the lookup isn’t an existing directory
RewriteCond %{REQUEST_FILENAME} !-d
#Check that the file isn’t index.php (avoid looping)
RewriteCond %{REQUEST_URI} !^index\.php$
#Force all .html lookups to the index file
RewriteRule (.+)*\.html index.php?nav=$1 [QSA,L]
#Note: QSA=query string append;L=Last, no more rules

This will rewrite all paths ending in “.html” to your index file.

From there, it’s simply a case of tailoring the rewrite to your requirements.

Checkout the mod_rewrite cheat sheet for more help on rewrites.

If you ARE using PHP, a better way might be to just hand over ALL the path information to your “index.php” and handle it from there, the rewrite to do that looks something like this:

RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^index\.php$
RewriteRule ^(.+)$ index.php/$1 [QSA,L]

As per above this will only rewrite paths that don’t exist.

In your “index.php”, you can parse $_SERVER['PATH_INFO'] (and sometimes $_SERVER['ORIG_PATH_INFO']) for the path information.

2 Comments »

  1. Ben Steele said,

    January 28, 2007 @ 10:52 am

    Multiviews is also an option here, although it takes a little bit more time preparing your code the finished url output is excellent.

  2. Zeeshan said,

    August 1, 2008 @ 2:30 pm

    I would have to agree. Using a resource extensive module to act as glue between your application and the HTTPd is wasteful. Consider using the PATH_INFO environment via MultiViews, as Ben Steele highlighted. It’s also possible to use it via SetAction and ForceType.

RSS feed for comments on this post · TrackBack URL

Leave a Comment