gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 02:52:20 24 4
gpt4 key购买 nike

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

我需要使用来自 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com