【问题标题】:Apache RewriteRule unexpected behaviour when two rules match URL at one moment (add path info postfix)当两个规则同时匹配 URL 时,Apache RewriteRule 出现意外行为(添加路径信息后缀)
【发布时间】:2023-03-06 18:38:02
【问题描述】:

我正在使用 apache rewrite_mod (Apache/2.2.17 Win32) 并遇到非常奇怪的 rewriteRule 行为。

我的脚本主要从 nice url 重写名为 f1 .. f<infinity> 的无限过滤器参数,并在循环中将它们添加为查询变量、添加路径作为查询和页码。

它完美无缺,但如果我添加另一个规则(脚本中的最后一条规则)

RewriteRule   ^(.+)\.html$                       /index.php?path=$1.html [QSA]

对于另一种情况,它会在脚本开始时更改重写器的执行。




输入网址:

http://testing.loc/some/thing/index0-f1-nice-cars-f2-planes-f3-karts-f4-bike.html

所有重写后 PHP 的预期结果:

$_SERVER[QUERY_STRING] => path=some/thing/&page=0&f1=nice-cars&f2=planes&f3=karts&f4=bike
$_SERVER[SCRIPT_NAME] => /index.php

脚本看起来像这样(下一部分功能完美):

# from: some/thing/index0-f1-nice-cars-f2-planes-f3-karts-f4-bike.html
# to:   some/thing/index0.html?f=-f1-nice-cars-f2-planes-f3-karts-f4-bike

RewriteRule   ^(.*/?index[0-9]*)((?:-f[0-9]+-.+?)+)\.html$   /$1.html?f=$2 [QSA]

# from: some/thing/index0.html?f=-f1-nice-cars-f2-planes-f3-karts-f4-bike
# to    index.php?path=some/thing/&page=0&f=-f1-nice-cars-f2-planes-f3-karts-f4-bike

#              (   $1   )     (  $2  )
RewriteRule   ^(.+/{0,1})index([0-9]*)\.html$    /index.php?path=$1&page=$2 [QSA]

# while in f is something like "f1-nice-cars" (for example)
# remove "f1-nice-cars" from f and add as query "f1=nice-cars"

#                              (%1)    (   %2  ) ( %3)(       %4       )
RewriteCond   %{QUERY_STRING} ^(.*)&f=-(f[0-9]+)-(.+?)((?:-f[0-9]+-.+)*)$ 
RewriteRule   ^index\.php$                       /index.php?%1&%2=%3&f=%4 [L]

# remove empty "f=" from query

RewriteCond   %{QUERY_STRING} ^(.*)&f=$ 
RewriteRule   ^index\.php$                       /index.php?%1

这里,规则之后是 url 的形状:

index.php?path=some/thing/&page=0&f1=nice-cars&f2=planes&f3=karts&f4=bike

如果脚本中没有下一条规则,一切都会完美运行。但是如果我添加它,这条规则本身什么也不做,但是 rewrite_mod 在脚本开始时添加了更多内容。

# rewrite rule for other paths without filters

RewriteRule   ^(.+)\.html$                       /index.php?path=$1.html [QSA]

其实所有脚本运行后的结果是:

index.php?path=/some/thing/index0.html/some/thing/index0&f1=nice-cars&f2=planes&f3=karts&f4=bike

【问题讨论】:

  • 您是否通过删除除此“问题”规则之外的所有规则并为其提供“规则后”网址来证明/调试这一点?
  • 我测试过了,“问题”规则什么也没做。
  • 那我不明白你的问题。 ^(.+)\.html$ 应该什么都不做:你的网址不以html 结尾。你为什么不改写你的问题来询问你想要的正则表达式/规则 - 提供示例输入和输出
  • 请在批评我的问题之前通读一遍。我说,那应该什么都不做,但在正常运行时做一些奇怪的事情。我给出所有测试输出并写下正常运行时发生的情况以及是否将其拆分为非问题和问题部分。我搜索了更多,发现了一些有趣的东西。它被称为“添加路径信息后缀”操作,在某些情况下使用重写 mod,它被视为错误。这个时候,我不知道它到底是什么,但我会更多地搜索。当一个 .htacces “fit” url 中的两个规则,然后 rewrite_mod 添加一些内容到替代时,可能会发生这种情况。

标签: regex mod-rewrite url-rewriting apache2


【解决方案1】:

我找到了这个问题的解决方案。 当 2 个规则在 .htaccess 的一次传递中匹配 URL 时,apache rewrite_mod 使用方法“添加路径信息后缀”(类似于错误或功能),这会破坏请求的路径。所以当我在这两条规则中添加标志 [L] 时,结果是好的。

我认为 apache 按顺序传递 .htaccess 并且对下一个规则无关紧要...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-30
    • 2016-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多