Apache mod_alias RedirectMatch除特定模式之外的所有内容

时间:2014-10-16 08:40:07

标签: regex apache redirect mod-alias apache2.4

好的旧正则表达式让我疯狂。

我需要将Apache 2.4中的所有流量从HTTP重定向到HTTPS,除了“/ bt / sub / [a_few_endings]”,使用mod_alias的重定向(不能使用mod_rewrite)。

我在我认识的所有在线测试人员中测试了以下正则表达式(例如http://regex101.com/)并且都确认正则表达式确实应该匹配除了我不希望它匹配的URL之外的所有内容:

^/(?!bt/sub/(went_active|success|cancel|expired)).*$ 

据我所知,这应与 http ://local.mysite.com中的所有相匹配,并将其重定向至 https ://local.mysite.com,除了以下四个:

仍然,Apache重定向所有内容,包括我不想重定向的上述URL。

我在SO中发现了几个类似的问题,但大多数都是根据mod_rewrite回答的,这不是我想要/需要的,而且人们说有用的那些对我没用。

这是我目前的虚拟主机配置:

<VirtualHost *:80> 
    ServerName local.mysite.com 
    RedirectMatch 302 ^/(?!bt/sub/(went_active|success|cancel|expired)).*$ https://local.mysite.com 
    DocumentRoot /home/borfast/projects/www/mysite/public 
    #Header set Access-Control-Allow-Origin * 
    SetEnv LARAVEL_ENV localdev 

    <Directory /home/borfast/projects/www/mysite/public/> 
        Options All 
        DirectoryIndex index.php 
        AllowOverride All 
        Require all granted 
    </Directory> 
</VirtualHost>

请帮助并防止我发疯:)


更新: 有一些奇怪的事情发生了:显然,当找到请求的URL /路径时,Apache会忽略RedirectMatch中的表达式并重定向客户端,即使RedirectMatch告诉它不要。

为了测试这个,我在一个单独的VM中创建了一个新的虚拟主机,这个虚拟主机安装了Ubuntu Trussty 64,并装载了Apache 2.4。这个新的虚拟主机只包含ServerName,RedirectMatch和DocumentRoot指令,如下所示:

<VirtualHost *:80>
    ServerName testing.com
    RedirectMatch 302 ^/(?!bt/sub/(went_active|success)$).*$ https://othersite.com/

    DocumentRoot /home/vagrant/www
</VirtualHost>

我创建了目录/home/vagrant/www/bt/sub/went_active,以确保Apache可以访问两个可能的URL中的至少一个。尝试访问http://testing.com:8080时,我会按预期重定向。

然后奇怪的是:当访问http://testing.com:8080/bt/sub/went_active时,与我创建的目录匹配的URL,我仍然被重定向,即使我不应该,但是当访问http://testing.com:8080/bt/sub/success时,我不知道t被重定向,而是获得403 Forbidden。

我可能会对此失去理智,但似乎当Apache发现它可以提供请求并且它与RedirectMatch中的正则表达式匹配时应该阻止重定向时,它决定忽略正则表达式并进行重定向。三封信:WTF?!?!?!

2 个答案:

答案 0 :(得分:10)

正如评论中所说 - 使用mod_rewrite更容易。可能的解决方案

RewriteEngine On
RewriteCond %{REQUEST_URI} !^/bar/(abcd|baz|barista|yo)$ [NC]
RewriteRule ^ http://site/ [R=301,L]

另一个(针对.htaccess,初始/已从RewriteRule中删除)

RewriteEngine On
RewriteRule !^bar/(abcd|baz|barista|yo)$ http://site/ [R=301,L,NC]

RedirectMatch

的解决方案
RedirectMatch permanent ^(?!/bar/(abcd|baz|barista|yo)$).* http://site/

所有工作都很完美,您在测试/调试状态下可能遇到的问题是浏览器缓存301响应。因此,当您尝试检查或编写正确的代码时 - 请使用302响应,而不是301。如果不需要不区分大小写,请删除NC标志。

答案 1 :(得分:1)

请参阅this one

^\/.*(?<!foo\/bar\/(aaa|bbb|ccc|ddd))$

匹配/后跟任何内容,除非字符串的结尾前面是/ foo / bar /(aaaa | bbb ...)

(?<!是附加在字符串$末尾的负面lookbehind,它会检查它不可能匹配字符串结尾之前的内容。

如果您的实际情况不像您的例子那样静态,请为查询部分提供实际数据。