我有一个rewritemap,其中包含要重定向的域的列表。目前,我必须在重写映射中列出www.foo.com和foo.com。我想知道是否有办法在同一行中同时对www和非www进行rewritecond检查。
# Rewrite Map
foo.com file.php
www.foo.com file.php
# modrewrite
RewriteCond ${domainmappings:%{HTTP_HOST}} ^(.+)$ [NC]
RewriteCond %1 !^NOTFOUND$
RewriteRule ^.*$ www.domain.com/%1 [L,R=301]
我尝试做类似(www。)%{HTTP_HOST}或^(www。)%{HTTP_HOST}的操作,但是没有运气。
最佳答案
这应该做到这一点:
RewriteCond %{HTTP_HOST} ^(www\.)?(.+)
RewriteCond ${domainmappings:%2} ^(.+)$ [NC]
RewriteRule ^ /%1 [L,R=301]
第一个
RewriteCond
将删除可选的www.
前缀。然后将其余部分用作第二个RewriteCond
中的重写映射的参数。如果找不到匹配项,纯文本文件重写映射将返回一个空字符串:
If the key is found, the map-function construct is substituted by SubstValue. If the key is not found then it is substituted by DefaultValue or by the empty string if no DefaultValue was specified.
因此,如果满足第二个条件(请注意
^(.+)$
),那么将找到一个匹配项,并且%1
将包含SubstValue(在这种情况下为file.php
)。
关于regex - 如何在rewritecond中匹配www和非www?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4566753/