Conditional “OR” operation in RewriteRule

纵饮孤独 提交于 2020-01-05 05:39:50

问题


I want to redirect certain urls of my old website to the new website. This redirection to new website is conditional i.e if query param contains key "site" with value as "eu", "jp" or "in" then only redirect otherwise do not.

 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]

With above configuration it works well for path "/fetchHomePage" but for other paths in the URLs ("/fetchFirstPage", "/fetchSecondPage" and "/fetchThirdPage") browser is always redirecting to the new website irrespective of what the site param is there in the query parameter.


回答1:


You may follow one of these method :

Here you need to add the condition for all the rules.

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]

OR

You can also write multiple rules but for that you need to remove the L flag from all the rules except last rule.

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 = Last

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.

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



来源:https://stackoverflow.com/questions/48496190/conditional-or-operation-in-rewriterule

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!