使用 apache 的 mod_rewrite 解析 SEO 友好的 URL

2021-12-21 00:00:00 php .htaccess seo mod-rewrite

我如何转换类似的东西

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?

with mod_rewrite?

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

Can I make the reverse conversion as well with mod_rewrite, or would I have to parse it through PHP?

推荐答案

这应该适用于两者:

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:

You can also make it more precise so only the two request are rewritten and only digits are accepted as id:

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

相关文章