使用.htaccess文件向URL添加$ title

时间:2014-09-12 22:21:42

标签: php apache .htaccess mod-rewrite redirect

我最近得到了以下答案:.htaccess rewrite url does not work

我现在想将每个id的数据库中的标题添加到URL中。从我在互联网上看到的内容来看,这似乎是可能的。大多数情况下,我在每个php文件中都有$title,它引用了db中的标题。

目前我在我当前的.htaccess文件中使用它:

Options +FollowSymLinks -MultiViews

RewriteEngine On
RewriteBase /

# Redirect cars.php?cars_item=231 to cars/231/
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+cars/cars\.php\?cars_item=([^&\s]+) [NC]
RewriteRule ^ /cars/%1 [R=302,L]

# Internally forward cars/231/ to cars.php?cars_item=231
RewriteRule ^cars/([0-9]+)/?$ /cars/cars.php?cars_item=$1 [NC,L]

以下为href:<a href=\"cars/$id\"/>$title</a>

所以我希望拥有的URL如下所示。基本上我需要将标题添加到当前URL并用短划线替换标题中单词之间的空格。

http://www.domain.com/cars/543/new-porsche-is-out

  • 汽车 - &gt;子文件夹
  • 543 - &gt; $ id(来自数据库)
  • new-porsche-is-out - &gt; $ title(来自数据库)

1 个答案:

答案 0 :(得分:0)

您最后可以更改最后一条规则以允许标题:

# Internally forward cars/231/title to cars.php?cars_item=231
RewriteRule ^cars/([0-9]+) /cars/cars.php?cars_item=$1 [NC,L,QSA]