Apache If 语句不起作用

Apache If 语句不起作用

我的旧网站上有大约 25000 个 URL,其中的 URL 包含 abc。

我想在我的 apache 配置中使用 3 个 DBM 文件。

目标是如果 URL 不包含 abc,即,http://example.com/1234.htm我不希望查看 abcredirects.DBM 文件。

如果 URL 确实包含 abc,即,http://example.com/abc1234.htm我只希望查看 abcredirectsDBM 文件。

我试图在我的 Apache 中使用 if 语句,但是每次我使用该<If>块时,我放入其中的任何内容似乎都会被忽略。

我用很多不同的方法更改了该<If "%{REQUEST_URI} =~ m#^abc#">行,但没关系。如果我删除该<if>块,所有重定向都会按预期工作。

为什么我的<if>块被忽略了?没有错误,而且根据日志http://example.com/abc1234.htm(我假设)没有评估为真,所以我不确定还要检查什么。

[root@mail conf]# httpd -v
Server version: Apache/2.4.6 (CentOS)
Server built:   Jun 27 2018 13:48:59


<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteMap abcredirects "dbm:/etc/httpd/conf/dbm/abcredirects.dbm"
        <If "%{REQUEST_URI} =~ m#^abc#">
        RewriteCond ${abcredirects:$1} !=""
        RewriteRule ^(.*) /${abcredirects:$1} [R=301,L]
        </If>
    RewriteMap shortalias "dbm:/etc/httpd/conf/shortalias.dbm"
    RewriteCond ${shortalias:$1} !=""
    RewriteRule ^(.*) /${shortalias:$1} [R=301,L]
</IfModule>

<VirtualHost *:80>
    DocumentRoot /var/www/sites/me
    ServerName example.com
    DirectoryIndex index.htm
    Options +FollowSymLinks
    RewriteEngine On
    RewriteOptions Inherit
    RewriteMap otherredirects "dbm:/etc/httpd/conf/otherredirects.dbm"
    RewriteCond ${otherredirects:$1} !=""
    RewriteRule ^(.*) /${otherredirects:$1} [R=301,L]
</VirtualHost>

我曾经见过并尝试过的 Serverfault 问题:

如果 URL 具有特定模式,apache 强制重定向到 https

在 Apache 中重定向、更改 URL 或将 HTTP 重定向到 HTTPS - 您想了解但又不敢问的有关 Mod_Rewrite 规则的一切

答案1

<If "%{REQUEST_URI} =~ m#^abc#">

服务器REQUEST_URI变量始终以斜线(URL 路径的开头)开头,因此正则表达式m#^abc#永远不会匹配。您需要改用正则表达式m#^/abc#。(假设这不是您已经尝试过的“不同方法”之一?)

我还会避免在 vHost 和服务器之间拆分配置 - 除非有特殊要求?这会使 mod_rewrite 的问题变得复杂,因为虚拟主机context 通常会覆盖服务器上下文,因此您需要使用 mod_rewrite 继承(您正在这样做) - 但这会变得不必要地混乱。(inherit选项继承父指令在后面当前上下文,这可能不是您所期望的。

您的问题的其余部分似乎与您最近的问题有交叉:

相关内容