user friendly urls

Posted in PHP by

User friendly urls are often used for search engine optimization, but more important, they improve the browsing experience of the users. Rewritten urls can be done with mod_rewrite or similar methods (like redirect settings of web-servers).

requirements A webserver with a rewrite method. If you are a apache user, make sure "LoadModule rewrite_module modules/" is active. (Look at http.conf and uncomment if needed. Comments are "#").

setup Create this in the root folder of your script. i.e: "www\userfriendlyurls" where "www" is your webserver root dir.

RewriteEngine On
RewriteBase /userfriendlyurls
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?q=/$1 [QSA,L]
Adjust this to your needs. Change the RewriteBase to your folder name, if your scripts runs in root, then RewriteBase is "/". The query string (everything after the question mark) will be appended.

adjust your script The best option is to have a global config option in your script, that toggles user friendly urls. Every request sent to the server runs trough this steps: 1) Checks if Directory or File exists, if yes output them else continue. 2) Rewrite the url i.e.: from /userfriendlyurls/company/about to /userfriendlyurls/index.php/company/about 3) Runs your script. You can access the query in "$_SERVER['PATH_INFO']".

where to go from here You can create your own hand-written routing script. Use index.php as your startup and wrap your php scripts into classes. In one of the next articles, you will learn how real world scripts are using routers and more about language patterns like MVC, DRY and KISS.

Published at , Updated at 2011-10-25

next: Secure User Input with Markdown prev: Class