regex - 如何在rewritecond中匹配www和非www?

标签 regex apache mod-rewrite rewritemap

我有一个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/

相关文章:

php - preg_replace 当不在双引号内时

python - 使用 python 语言的正则表达式

PHP 和正则表达式 : Split a string by commas that are not inside brackets (and also nested brackets)

php - Apache,如何处理未知的 php 文件,如标准 URL?

apache - 使用apache rewrite时如何隐藏URL更改?

.htaccess - AWS Elasticbeanstalk 单实例强制 SSL 重定向循环

javascript - 如何使用正则表达式解析这种格式(ICAO飞行计划备注)?

apache - mod_expires 未在 JPEG 图像上设置缓存控制 header

django - SSL 收到超过最大允许长度的记录(FF/Django/StartSSL/Windows)

Apache 在使用 http 时显示默认页面而不是 https