Url manipulation with mod_rewrite and php-catcher for beginners

Submitted by n8coder on Tue, 05/26/2009 - 02:56

Url manipulation is one of the hottest areas on the new generation web (2.0). It provides more security and flexibility. It is user and search-engine friendly. The most popular combination is Apache-webserver + mod_rewrite + server-side catcher(mostly a php-file). In this tutorial we use very short examples to make it easy for newbies.

Why url manipulation & mod_rewrite?

  1. more security: hide file location
  2. shorter urls without file extensions like .html
  3. easy to remember / recommend urls
  4. search engine friendly
  5. easy to manage structure

Example:
old url:
example.com/some-path/and-file.php?long=string&with=bloody&session_id=a5kg7hirh39573...

new url:
example.com/2009/05/25/article-about-history

Can you tell a friend the first url on the phone or send with a sms?

Files:

  1. .htaccess
  2. catch.php
  3. page1.html
  4. page2.html




.htaccess


RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ catch.php?p=$1 [L,QSA]

"RewriteCond %{REQUEST_FILENAME} !-f" means if requested path is not an existed file
"RewriteCond %{REQUEST_FILENAME} !-d" means if requested path is not a real directory




catch.php


$p = $_GET[p]; // p means page or path

// use white-lists against possible code-injections

$my_pages["my/first/url"] = "page1.html";
$my_pages["second-url"] = "page2.html";

if( $my_pages[$p] && file_exists( $my_pages[ $p ] ) ){

include( $my_pages[ $p ] );

} else {

echo "Page not found: $p";

}




page1.html


Welcome to page 1!




page2.html


This is page 2.

Now test it with calling urls on your website:
yoursite.com/my/first/url
yoursite.com/second-url
yoursite.com/non/existing/path

Links for detailed information & guides:
http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html
http://en.wikipedia.org/wiki/Rewrite_engine
http://redmine.lighttpd.net/wiki/lighttpd/Docs:ModRewrite
http://msdn.microsoft.com/en-us/library/ms972974.aspx
http://www.sitepoint.com/article/guide-url-rewriting/