rewriting numeric id's (as discussed in the FAQs)

New to mod_rewrite? This is a good place to start.

rewriting numeric id's (as discussed in the FAQs)

Postby unclepauly » Sat May 31, 2008 12:39 pm

hi,

like alot of people, im totally new to mod-rewrite. im using it to enable google to see my web site better.

the FAQs talk about my problem. basically, i have index.php, with a parameter to identify what product to load. for example:

Code: Select all
www.mywebsite.com/index.php?product=202


however, product 123 is actually shoes (its not really but for the purpose of explanation it can be). ive got loads of products, each with a different numberic ID. what i actually want to display in the address bar is:

Code: Select all
www.mywebsite.com/shoes


so in my .htaccess file i have:

Code: Select all
RewriteEngine on
RewriteRule ^(allproducts)$ /index.php?product=193 [NC,L]
RewriteRule ^(shoes)$ /index.php?product=202 [NC,L]
RewriteRule ^(hats)$ /index.php?product=142 [NC,L]
RewriteRule ^(pants)$ /index.php?product=141 [NC,L]
etc
etc


the list is quite long, and rather than have a seperate rule for each product i would like to have one general rule.

of the 4 suggestions in the FAQs, the first three are not possible solutions. i am trying to understand the 4th suggestion - could someone elaborate on this please ?

thanks !
unclepauly
 
Posts: 1
Joined: Sat May 31, 2008 12:18 pm

Postby richardk » Sun Jun 01, 2008 12:05 pm

A general rule
Code: Select all
Options +FollowSymLinks

RewriteEngine On

# If it's not a request for an existing file
RewriteCond %{SCRIPT_FILENAME} !-f
# and it's not a request for an existing directory
RewriteCond %{SCRIPT_FILENAME} !-d
# rewrite to a PHP script.
RewriteRule ^(.+)$ /rewrite.php?mr_product_name=$1 [QSA,L]


The script (rewrite.php) takes the product name and gets the product ID
Code: Select all
<?php

# Set up an array that links product name and product ID. How you create this
# array is up to you. You may be able to build it automatically from your
# database. If you do, i suggest you use caching.
$mr_product_name_to_id = array(
  'allproducts' => 193,
  'shoes' => 202,
  'hats' => 142,
  'pants' => 141,
  );

# Check if the product name is in the array.
if(array_key_exists($mr_product_name_to_id, $_GET['mr_product_name']) === true)
{
  # It's in the array, set the correct ID.
  $_GET['product'] = $mr_product_name_to_id[$_GET['mr_product_name']];
  # Delete the array and the name (they're no longer needed).
  unset($mr_product_name_to_id, $_GET['mr_product_name']);
  # Include index.php to run the original script with the ID.
  include('./index.php');
}
else
{
  # It was not found, send a 404 header.
  header('Content-Type: text/html', true, 404);
?>
Your 404 page here.
<?php
}
richardk
 
Posts: 8800
Joined: Wed Dec 21, 2005 7:50 am


Return to Beginner's Corner

Who is online

Users browsing this forum: MSN [Bot] and 3 guests