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?
- more security: hide file location
- shorter urls without file extensions like .html
- easy to remember / recommend urls
- search engine friendly
- 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:
- .htaccess
- catch.php
- page1.html
- 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"; if( $my_pages[$p] && file_exists( $my_pages[ $p ] ) ){ include( $my_pages[ $p ] ); } else { echo "Page not found: $p"; }
$my_pages["second-url"] = "page2.html";
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/
- Log in to post comments