RewriteRule 中的条件 "OR" 操作

Conditional "OR" operation in RewriteRule

我想将旧网站的某些网址重定向到新网站。重定向到新网站是有条件的,即如果查询参数包含键 "site",值为 "eu"、"jp" 或 "in",则仅重定向,否则不重定向。

 RewriteCond %{QUERY_STRING} (?:^|&)site=(eu) [NC,OR]
 RewriteCond %{QUERY_STRING} (?:^|&)site=(in) [NC,OR]
 RewriteCond %{QUERY_STRING} (?:^|&)site=(jp) [NC]
 RewriteRule ^/?fetchHomePage.action$ https://example.com/%1? [R=301,L,NC]
 RewriteRule ^/?fetchFirstPage.action$ https://example.com/firstpage/%1? [R=301,L,NC]
 RewriteRule ^/?fetchSecondPage.action$ https://example.com/fetchsecondpage/%1? [R=301,L,NC]
 RewriteRule ^/?fetchThirdPage.action$ https://example.com/fetchThirdPage/%1? [R=301,L,NC]

通过上述配置,它适用于路径“/fetchHomePage”,但对于 URL 中的其他路径(“/fetchFirstPage”、“/fetchSecondPage”和“/fetchThirdPage”)浏览器总是重定向到新网站,无论查询参数中的站点参数是什么。

您可以采用以下方法之一:

此处需要为所有规则添加条件

RewriteCond %{QUERY_STRING} (?:^|&)site=(eu|in|jp)(?:&|$) [NC]
RewriteRule ^/?fetchHomePage.action$ https://example.com/%1? [R=301,L,NC]

RewriteCond %{QUERY_STRING} (?:^|&)site=(eu|in|jp)(?:&|$) [NC]
RewriteRule ^/?fetchFirstPage.action$ https://example.com/firstpage/%1? [R=301,L,NC]

RewriteCond %{QUERY_STRING} (?:^|&)site=(eu|in|jp)(?:&|$) [NC]
RewriteRule ^/?fetchSecondPage.action$ https://example.com/fetchsecondpage/%1? [R=301,L,NC]

RewriteCond %{QUERY_STRING} (?:^|&)site=(eu|in|jp)(?:&|$) [NC]
RewriteRule ^/?fetchThirdPage.action$ https://example.com/fetchThirdPage/%1? [R=301,L,NC]

您也可以编写多个规则,但为此您需要从除最后一条规则之外的所有规则中删除 L 标志。

RewriteCond %{QUERY_STRING} (?:^|&)site=(eu|in|jp)(?:&|$) [NC]
RewriteRule ^/?fetchHomePage.action$ https://example.com/%1? [R=301,NC]
RewriteRule ^/?fetchFirstPage.action$ https://example.com/firstpage/%1? [R=301,NC]
RewriteRule ^/?fetchSecondPage.action$ https://example.com/fetchsecondpage/%1? [R=301,NC]
RewriteRule ^/?fetchThirdPage.action$ https://example.com/fetchThirdPage/%1? [R=301,L,NC]

L = 最后一个

The [L] flag causes mod_rewrite to stop processing the rule set. In most contexts, this means that if the rule matches, no further rules will be processed. This corresponds to the last command in Perl, or the break command in C. Use this flag to indicate that the current rule should be applied immediately without considering further rules.

参考:https://httpd.apache.org/docs/2.4/rewrite/flags.html