regex - Apache mod_alias Redirect匹配除特定模式之外的所有内容

标签 regex apache redirect mod-alias apache2.4

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

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

我在我认识的所有在线测试人员中测试了以下正则表达式(例如 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 告诉它不要这样做。

为了测试这一点,我在一个新安装了 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 时,我没有被重定向,而是得到了 403 Forbidden。

我可能对此失去了理智,但似乎当 Apache 发现它可以服务该请求并且它与 RedirectMatch 中的正则表达式匹配(应该阻止重定向)时,它决定忽略正则表达式并无论如何进行重定向。三个字母:WTF?!?!?!

最佳答案

正如评论中所说 - 使用 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。如果不需要不区分大小写,请删除 Ncflags。

关于regex - Apache mod_alias Redirect匹配除特定模式之外的所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26399826/

相关文章:

java - 正则表达式模式与我无法遵循的模式之一相匹配?

java - Apache Solr 无法存储嵌套 JSON 数据

python tornado用户认证,然后通过apache反向代理

php - 将 URL 重定向到正确的用户页面

C++11 regex_error - 为什么? (代码 : 2)

javascript - 如何使用正则表达式或任何其他解决方案从复杂字符串中获取所有子字符串?

regex - vim:从反向引用中替换字符

php - 将我在 Apache 服务器上的网站传输到 AWS

.htaccess - CDN 图像重定向(避免使用 htaccess 的重定向循环)

redirect - 站点性能 : rel=canonical vs redirect 301