重写规则:用php创建链接并用Name替换ID

时间:2014-11-30 16:42:13

标签: php .htaccess mod-rewrite

在我爆炸之前,我想问你以下几点。

我有这个:

http://subdomain.example.com/index.php?page=item&item_id=42

我想要的是这个:

http://subdomain.example.com/item/name-of-the-item/

我的解决方案:

RewriteEngine on
RewriteRule ^([^/]*)/([^/]*)/$ /index.php?page=$1&item_id=$2 [L]

告诉我:

http://subdomain.example.com/item/42/

到目前为止这个工作正常但我如何获得名称而不是纯粹的id? 我已将所有内容存储在数据库中,这意味着id具有特定名称。 例如,ID = 42,Name = Test

这是我构建我的hrefs的方式:

<a href=" <? echo 'item/'.$controller->getItem($id)->getId(); ?> /">

当我与getId()交换getName()时,他们工作了http://subdomain.example.com/item/test/,但网站只是空白而没有内容。

如果你们中的任何一个人能够指出我在这里错过的方向,我将不胜感激。

1 个答案:

答案 0 :(得分:2)

更改您的信息页:

http://subdomain.example.com/index.php?page=item&item_id=42

有关:

http://subdomain.example.com/index.php?page=item&item_name=Test

(页面的PHP代码需要进行更改!)

之后,您可以使用:

RewriteRule ^([^/]+)/([^/]+)/?$ /index.php?page=$1&item_name=$2 [L]

如果您始终使用带有数字的ID和带有字母的item_name,您甚至可以将两者混合使用:

RewriteRule ^([^/]+)/(\d+)/?$ /index.php?page=$1&item_id=$2 [L]
RewriteRule ^([^/]+)/([^/]+)/?$ /index.php?page=$1&item_name=$2 [L]