views:

30

answers:

2

I have my link like this /product.php?id=1

I want to rewrite that in .htaccess like /productname/id or /productname/1.

Can you help me guys, I’m using PHP?

A: 

I'll offer you two approaches.

The first will be the simplest. You probably want to use mod_rewrite in Apache. Then post this question on serverfault.com.

Hint: configuration (in your .htaccess file) will probably be something like:

RewriteEngine On
RewriteRule ^/product.php?id=([0-9]+)$ /productname/$1

The second approach is to have your product.php script tell the calling browser to load a new URL. To do this consider something like:

<?php
  $id = $_GET['id'];

  if ( $id > 0 ) {
    /* Redirect browser */
    header("Location: http://www.mydomain.com/productname/$id");
    /* Make sure that code below does not get executed when we redirect. */
    exit;
  }
?>
PP
A: 

For doing that, you will either need the product name to be fetched along with the id in order to use it in the rewrite expression.

You might also want to explore RewriteMap where you can map a list of product ids to product names. Obviously, you would do this only if you have a limited number of products.

If the number of products is dynamic and change too frequently, I suggest you retrieve the product name when you retrieve the id.

Adarsh R