2009-06-10 38 views
3

如何转换类似使用Apache的mod_rewrite解析SEO友好的URL的

me.com/profile/24443/quincy-jones 

me.com/profile.php?id=24443

或类似

me.com/store/24111/robert-adams

me.com/store.php?id=24111 

用mod_rewrite?

我可以使用mod_rewrite进行反向转换,还是我必须通过PHP解析它?

回答

9

这应该两个工作:

RewriteEngine on 
RewriteRule ^([^/]+)/([^/]+).*$ $1.php?id=$2 [L] 

说明:

^   - beginning of the string 
([^/])  - first group that doesn't contain/
       will match both 'profile' and 'store' 
       will also be referenced by $1 later 
/   - first slash separator 
([^/])  - second group, id in your case 
       will be referenced by $2 
.*   - any ending of the request uri 
$   - end of request string 

您也可以使之更精确所以只有两个要求被重写,只有数字被接受为ID:

RewriteRule ^((profile|store))/(\d+).*$ $1.php?id=$2 [L] 
+0

+1,对于说明 – Starx 2012-11-02 05:00:28

2

确保您已启用mod_rewrite apache模块,然后:

RewriteEngine on 

RewriteRule ^/profile/([^/]*)/([^/]*)$ /profile.php?id=$1 [L] 

RewriteRule ^/store/([^/]*)/([^/]*)$ /store.php?id=$1 [L] 

您可能想要处理PHP中的逆向条件,特别是尾部名称部分(因为它不在原始URL中)。如果你想在mod_rewrite中没有名字来处理它,请确保你不会以双重重写(取决于你的规则的顺序)。此外,您可以使用[L](上一个)开关将规则作为最后一个使用(如果匹配,后续规则将被跳过)。

此外,可以制定更通用的重写规则,但您需要仔细考虑可能受到影响的其他URL。