Q1 :如何链接这两个条件,使其成为if BOTH A AND B, then proceed...
Q2 :如何使它们适用于下面的所有rewriteRules,而不仅仅是第一条规则?
RewriteCond %{REQUEST_URI} ^IMAGE-.*$ // if filename starts with IMG- and,
RewriteCond %{REQUEST_FILENAME} !-f // if file does exist, then proceed:
RewriteRule Rule1
RewriteRule Rule2
RewriteRule Rule3
# -- END IF -- STOP HERE -- #
最佳答案
这是使RewriteCond
堆栈应用于多个RewriteRule
的技巧,通过增加WTF's per minute对其进行排序。但这是配置而不是代码,因此这些规则不适用,对吧? :-)
1.环境变量
当您有许多RewriteCond
时,将它们的结果存储在一个环境变量中,然后在每条规则中进行测试将更为紧凑。
# Your RewriteCond stack.
RewriteCond %{REQUEST_URI} !^IMAGE-.*$ [OR]
RewriteCond %{REQUEST_FILENAME} -f
# Store environment variable.
RewriteRule ^ - [E=TRUE:YEP]
# Assert environment variable in remaining RewriteRule's.
RewriteCond %{ENV:TRUE} =YEP
RewriteRule Rule1
RewriteCond %{ENV:TRUE} =YEP
RewriteRule Rule2
RewriteCond %{ENV:TRUE} =YEP
RewriteRule Rule3
2.跳过标志
这个有点微妙。使用
[S]
或[skip]
标志,您可以导致整个RewriteRule
块被跳过。# Your RewriteCond stack.
RewriteCond %{REQUEST_URI} !^IMAGE-.*$ [OR]
RewriteCond %{REQUEST_FILENAME} -f
# If RewriteCond's match, skip the next RewriteRule.
RewriteRule ^ - [skip=1]
# Otherwise, this rule will match and the rest will be skipped.
RewriteRule ^ - [skip=3]
RewriteRule Rule1
RewriteRule Rule2
RewriteRule Rule3
这有点像if语句,其中
RewriteCond
是条件,RewriteRule
是代码块。您得到的重复较少,但是折衷之处是代码不清楚,并且每次在此 N
[skip=N]
中添加或删除规则时,都必须更新RewriteRule
。好吧,如果您仍在阅读,这里还会发现另外两个解决方案,它们使WTF's per minute达到并超过了临界点。它们仅用于娱乐,您将明白原因。
3.跳过没有N的标志
是的,有一种方法可以使用
[skip]
标志,而无需包括 N ,即您要应用RewriteRule
堆栈的RewriteCond
的数量。那就是...如果您在每个RewriteCond
之前添加一对RewriteRule
,并且是的,在末尾再添加一对。# Your RewriteCond stack.
RewriteCond %{REQUEST_URI} !^IMAGE-.*$ [OR]
RewriteCond %{REQUEST_FILENAME} -f
# If RewriteCond's match, skip the next RewriteRule.
RewriteRule ^ - [skip=1] # succeeded
RewriteRule ^ - [skip=2] # failed
RewriteRule Rule1
RewriteRule ^ - [skip=1] # succeeded
RewriteRule ^ - [skip=2] # failed
RewriteRule Rule2
RewriteRule ^ - [skip=1] # succeeded
RewriteRule ^ - [skip=2] # failed
RewriteRule Rule3
RewriteRule ^ - # no-op to cover for last [skip=2] rule
这里的技巧是,仅当
[skip=1]
成功时才处理每个RewriteCond
规则,并且仅当失败时才处理每个[skip=2]
规则。4. URL标记
使用URL的一部分来保持状态,然后在
RewriteRule
中对其进行匹配。# Your RewriteCond stack.
RewriteCond %{REQUEST_URI} !^IMAGE-.*$ [OR]
RewriteCond %{REQUEST_FILENAME} -f
# If RewriteCond's match, prepend bogus marker "M#" to internal URL.
RewriteRule .* M#$0
# All your RewriteRule's test for this marker plus whatever else.
RewriteRule ^M#.*Rule1
RewriteRule ^M#.*Rule2
RewriteRule ^M#.*Rule3
# Finally, don't forget to strip off the bogus marker.
RewriteRule ^M#(.*) $1
带有标记的新网址无效,但是最后一个
RewriteRule
将其还原,对吗?好吧,只有在它得到处理的情况下,因此在还原它之前,不要让标记URL退出这一轮的mod_rewrite处理。然后,您会得到404。关于apache - 多个重写条件:如何在一组规则之前链接它们?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5305987/