使用.htaccess重写URL

使用.htaccess重写URL,.htaccess,url-rewriting,seo,.htaccess,Url Rewriting,Seo,我有这样的链接/product.php?id=1 我想在.htaccess中重写它,比如/productname/id或/productname/1 我正在使用PHP。我将为您提供两种方法 第一个将是最简单的。您可能希望在Apache中使用。然后在serverfault.com上发布这个问题 提示:配置(在.htaccess文件中)可能类似于: RewriteEngine On RewriteRule ^/product.php?id=([0-9]+)$ /productname/$1 <

我有这样的链接
/product.php?id=1

我想在.htaccess中重写它,比如
/productname/id
/productname/1


我正在使用PHP。

我将为您提供两种方法

第一个将是最简单的。您可能希望在Apache中使用。然后在serverfault.com上发布这个问题

提示:配置(在
.htaccess
文件中)可能类似于:

RewriteEngine On
RewriteRule ^/product.php?id=([0-9]+)$ /productname/$1
<?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;
  }
?>
第二种方法是让
product.php
脚本告诉调用浏览器加载新的URL。要做到这一点,请考虑如下:

RewriteEngine On
RewriteRule ^/product.php?id=([0-9]+)$ /productname/$1
<?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;
  }
?>

为此,您需要将产品名称与id一起提取,以便在重写表达式中使用它

您可能还想探索
RewriteMap
,在这里您可以将产品ID列表映射到产品名称。显然,只有在产品数量有限的情况下,您才会这样做

如果产品的数量是动态的并且变化太频繁,我建议您在检索id时检索产品名称