【问题标题】:using apache's mod_rewrite to parse SEO friendly URL's使用 apache 的 mod_rewrite 来解析 SEO 友好的 URL
【发布时间】:2010-11-01 19:24:08
【问题描述】:

我如何转换类似的东西

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 解析它?

【问题讨论】:

    标签: php .htaccess mod-rewrite seo


    【解决方案1】:

    这应该适用于两者:

    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]
    

    【讨论】:

      【解决方案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。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-11
        • 2023-03-12
        • 2015-02-14
        • 2010-12-03
        • 2019-05-29
        • 2020-05-06
        相关资源
        最近更新 更多