Simple ForceType example for search engine friendly URLs

First of all, what are Search Engine Friendly URLs?

Compare the two URLs below:
URL A: http://mysite.com/main.php?category=1&page=88
URL B: http://mysite.com/main/balls/pingpong

URL B is easier to understand because it does not have a question mark, equals sign (=) and the ampersand (&).
The simpler the URL, the better it is.

Now we can use Apache’s ForceType directive to make our URLs Search Engine Friendly.
First thing you should do is to put this in your .htaccess file.


ForceType application/x-httpd-php

Quoted from devarticles.com

“The code above tells Apache this: “If someone requests a file called myscript - in our case, “main” (with no extension) then treat it as a PHP script and forward it to the application setup to handle PHP scripts”.”

And then make main containing the following code:

< ?php

$nav = $_SERVER[’REQUEST_URI’];
//echo ”
request uri: “.$nav;

$script = $_SERVER[’SCRIPT_NAME’];
//echo ”
script name: “.$script;

$nav = ereg_replace(”^$script”, “”, $nav);
//echo ”
nav after ereg_replace(script): “.$nav;

$nav = str_replace(”.html”, “”, $nav);
//echo ”
nav after str_replace(.html): “.$nav;

$vars = explode(”/”, $nav);
//echo ”
vars: after explode: “.$nav;

$category = “”;
$page = “”;

//then count how many “variables” are found
$count = sizeof($vars);
if ($count == 2)
{

$category = $vars[1];
require(”http://localhost/test.php?category=”.$category);

}
else if ($count == 3)
{

$category = $vars[1];
$page = $vars[2];
require(”http://localhost/test.php?category=”.$category.”&page=”.$page);

}
else if ($count ==4)
{

$category = $vars[1];
$page = $vars[2];
$inner_page = $vars[3];
require(”http://localhost/test.php?category=”.$category.”&page=”.$page.”&inner_page=”.$inner_page);

}

?>

and finally create a test php file that will receive the variables from main.php
test.php - this file receives all the variables from the require() found in main.php

< ?php

echo ”
CATEGORY IS: “.$_GET[’category’];
echo ”
PAGE: “.$_GET[’page’];
echo ”
INNER PAGE: “.$_GET[’inner_page’];

?>
THEN, run test.php in your browser…
http://localhost/main/balls/pingpong/white
http://localhost/main/rackets/tennis/wood
http://localhost/main/computers/internet/webdevelopment

then observe the results.

in test.php, you can do stuff with the passed variables - for example using $GET[’category’] in a mysql query to display all the available categories in the database

Note: this only works on Apache servers

any questions? post them below.

Subscribe to Rss Feed : Rss