带有Htaccess的漂亮url在url中显示产品名称,但用id调用产品


Pretty urls with Htaccess show product name in the url but call the product with the id

我试着用htaccess做一些类似的事情。

http://www.domain.com/product/fussball-in-munich/

但是菜单导航的链接是这样的,

<a href="product.php?id=10">Fussball</a>

我将通过ID调用产品,但我想在url中显示产品名称,

我用我的htaccess,但不工作,我想。

RewriteEngine On
RewriteBase /dev
RewriteRule ^index'.php$ - [L]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^angebot/([A-Za-z-'s0-9]+)$ /dev/product.php?product_id=$1 [NC]
Options +FollowSymlinks -MultiViews
RewriteRule ^(.+)('s|%20)(.+)$ /$1-$3 [R=301,QSA,L,NE]
我的php文件
 if (isset($_GET['product_id'])){
$product_id = strip_tags($_GET['product_id']);
getProductsById($product_id);

}

功能
$query = "SELECT * FROM `product` WHERE id='$product_id'";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
$count = $result->num_rows;
    if ($count === 1){
        echo "<div class='container mt50'>";
            while($row = $result->fetch_assoc()){
            echo '<strong>This Product has been found in the database </strong>' .$row['product_name'];

                }
                echo "</div>";

    }else{}

您的htaccess文件不知道任何关于产品id或其名称之间的关系,这都在您的DB中。您需要在php文件中编写所有这些代码。

在htaccess文件中,你只能有:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^angebot/([A-Za-z-'s0-9]+)$ /dev/product.php?product_name=$1 [L]

则所有其余的逻辑必须编码到php:

  1. 检查"product_name"是否设置
  2. 检查$_SERVER['REQUEST_URL']中是否有product.php
  3. 去掉那些让名字好看的东西(用空格代替"-")
  4. 在数据库中查找具有给定名称的产品并获取ID
  5. 获取ID,呼叫getProductsById($product_id)

然后反过来(如果浏览器访问了丑陋的URL,则重定向浏览器):

  1. 检查"product_id"是否设置
  2. 检查$_SERVER['REQUEST_URL']中是否有product.php
  3. 如果是,有人直接要求你的产品ID
  4. 使用ID,对产品名称进行db查找,清理产品名称,使其看起来不难看(可能空格更改为"-")
  5. 将浏览器重定向到新的URL