【问题标题】:Assistance with a RewriteRule using RewriteMap使用 RewriteMap 协助 RewriteRule
【发布时间】:2012-11-17 08:58:22
【问题描述】:

我对 mod_rewrite 还很陌生,我正在尝试让 RewriteMap 指令正常工作。非常感谢您在使用它时提供的帮助。

我们的网址格式如下:

example.com/section.php?xSec=[ID]

所以对于第 201 节,即“Apple iPad”,URL 是:

example.com/section.php?xSec=201

我想要的是将其重写为:

example.com/apple-ipads

我已经在 apache config 中定义了 RewriteMap txt 文件,使用以下行:

RewriteMap sections txt:/var/www/rewrites/sections.txt

此 txt 文件包含以下内容:

multifunction-printers 102
inkjet-printers 103
laser-printers 104
apple-ipads 201

我在 .htaccess 中尝试了以下重写规则:

RewriteRule ^/section.php?xSec=(.*) ${sections:$1}

这不起作用。我假设我的 RewriteRule 存在问题,或者我将 RewriteMap 指令放在配置文件中的错误位置。有什么建议吗?

提前致谢

丹尼尔

【问题讨论】:

    标签: apache mod-rewrite url-rewriting rewritemap


    【解决方案1】:

    你的地图是倒着的。应首先列出密钥。

    201 apple-ipads
    

    我认为您不应该在模式的开头包含 / 以及其他一些内容;即,假设您的 ID 只是数字,更好的模式是:

    RewriteRule  ^section\.php\?xSec=(\d+)$  ${sections:$1}  [nocase]
    


    更新

    我只需要在需要 grep 查询字符串的地方对 uri 做一些 htaccess 工作。这个excellent post 帮助很大。以前的模式不起作用。这个应该:

    RewriteCond   %{QUERY_STRING}   xSec=(\d+)$   [nocase]
    RewriteRule   ^section\.php$   ${sections:%1}?  [nocase,redirect=perm,last]
    

    如果要在key无法匹配(未测试)时默认使用原始查询字符串:

    RewriteCond   %{QUERY_STRING}   xSec=(\d+)$   [nocase]
    RewriteRule   ^section\.php$   ${sections:%1?|$0?id=%1}  [nocase,redirect=perm,last]
    


    更新 2

    最后一个示例中的语法是错误的,因为 ?在 ${} 函数的匹配侧。从那以后,我使用这样的方法更新了自己的规则:

    # mapped
    RewriteCond   %{QUERY_STRING}   xSec=(\d+)$   [nocase]
    RewriteCond   ${sections:%1|NOTFOUND}   !NOTFOUND   [nocase]
    RewriteRule   ^section\.php$   ${sections:%1}?  [nocase,redirect=perm,last]
    

    使用这组规则,只有带有映射(查询)键的 uri 会被重定向。

    干杯。

    【讨论】:

      【解决方案2】:

      你可以使用这个重写:

      RewriteRule ^/(.*) /section.php?xSec=${sections:$1|NOTFOUND}
      

      对于发送到的每个请求:

      example.com/apple-ipads
      

      你应该清楚地看到答案来自:

      example.com/section.php?xSec=201
      

      如果没有找到密钥,答案来自:

      example.com/section.php?xSec=NOTFOUND
      

      但你必须知道,这种重写是行不通的,例如当你有一个空格或其他可以被浏览器编码的字符(àèò...)时。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多