Ajax software
Free javascripts
↑
Main Page
You start by modifying
product.php
to include a reference to
url_redirect.inc.php
, and then call its
fix_category_product_url()
function:
<?php
// load library that handles redirects
require_once ‘include/url_redirect.inc.php’;
// redirect requests proper keyword-rich URLs when not already there
fix_category_product_url();
The
fix_category_product_url()
function is executed every time a product page is loaded, and verifies
if the URL used to reach the page is the “proper” one. The “proper” version of the URL is composed using a
helper function named
get_proper_category_product_url()
:
// redirects to proper URL if not already there
function fix_category_product_url()
{
// obtain the proper URL of the current category/product page
$proper_url = get_proper_category_product_url();
How
get_proper_category_product_url()
works is discussed in a second. For now, just assume the
$proper_url
variable contains something like
http://seophp.example.com/Products/Friends-
Shed-C2/AJAX-PHP-Book-P42.html
. As soon as you obtain this “proper” URL, you verify that the URL
used by the visitor to reach the product page matches:
// 301 redirect to the proper URL if necessary
if (SITE_DOMAIN . $_SERVER[‘REQUEST_URI’] != $proper_url)
{
The
$_SERVER[‘REQUEST_URI’]
returns the URL used to reach the page, without the domain name. For
example, if you navigate to
http://seophp.example.com/product.php?category_id=2&product_
id=42
,
$_SERVER[‘REQUEST_URI’]
will return
/product.php?category_id=2&product_id=42
. By
joining the domain name with this value, you obtain a complete URL.
If there is no match, you do a 301 redirect to the proper URL by setting the necessary header values:
// 301 redirect to the proper URL if necessary
if (SITE_DOMAIN . $_SERVER[‘REQUEST_URI’] != $proper_url)
{
header(‘HTTP/1.1 301 Moved Permanently’);
header(‘Location: ‘ . $proper_url);
exit();
}
Now look at
get_proper_category_product_url()
. This function starts by loading the product and
category IDs passed through the URL in the
$_GET
variable:
// returns the proper keyword-rich URL
function get_proper_category_product_url()
{
// retrieve product and category IDs from the query string
$product_id = $_GET[‘product_id’];
$category_id = $_GET[‘category_id’];
88
Chapter 4: Content Relocation and HTTP Status Codes
c04.qxd:c04 10:40 88
Ajax software
Free javascripts
→ R7