将php urls重写为另一个变量

I have 2 variables, $id and $product_name

I have urls for different products eg:

website.co.uk/product.php?id=123456

how can I change this to the product name variable:

website.co.uk/product.php?id=name+of+product

can this be done in php or will I have to use mod rewrite?

to something like

website.co.uk/product/name-of-product    ?

I have seen this from another post:

RewriteRule ^product/([A-Za-z0-9-]+)/?$ product.php?id=$1 [NC,L]

if id=$1 in the line above, how does it know which variable to choose from out of $id and $product_name ? Where do I specify which variable it should use?


I now have website.co.uk/product.php?id=123456&name=name-of-product

and would like to rewrite this to:

website.co.uk/123456/name-of-product

or

website.co.uk/product/123456/name-of-product

You specify which variable to use by subpattern which is defined by () and numbered by $1 $2 in url

You can use something like

RewriteRule ^product/(/w+)/([A-Za-z]+)?$ product.php?id=$1&product_name=$2 [NC,L]
  • /w+ will fit 0-9A-Za-z which defines your $id
  • [A-Za-z]+ will work for product name

You can get these variables in PHP using $_GET['id'] to get id or $_GET['product_name'] to get product name.

mod_rewrite is not able to summon unknown information out of thin air. If you have a numeric id in your url, it cannot summon a product name out of thin air. If you use the pretty url /product/name-of-product you'll need to look up the name of the product in your database:

Use something like this in your .htaccess:

RewriteRule ^product/([^/]+)$ /product.php?name=$1 [L]

And this in your php file:

<?php
  if( isset( $_REQUEST['id'] ) ) {
    $name = getNameFromId( intval( $_REQUEST['id'] ) );
    header( "HTTP/1.1 301 Moved Permanently" );
    header( "Location: /product/{$name}" );
    exit();
  } else if( isset( $_REQUEST['name'] ) ) {
    $row = getRowFromName( $_REQUEST['name'] );
    if( $row === NULL ) {
      require( "404.php" );
      exit();
    }
    doStuff( $row );
  } else {
    //The heck? Neither of those set?
    require( "404.php" );
    exit();
  }