简体   繁体   English

正则表达式 - 如何匹配除特定模式之外的所有内容

[英]Regex - how to match everything except a particular pattern

I'm using Apache and I want to redirect all received request to the ssl virtual host.我正在使用 Apache,我想将所有收到的请求重定向到 ssl 虚拟主机。

So I have the following line in the regular http virtual host:所以我在常规 http 虚拟主机中有以下行:

RedirectMatch (.*) https://www.mydomain.com $1 RedirectMatch (.*) https://www.mydomain.com $1

which basicaly replace $1 by everything.这基本上用所有东西代替了 1 美元。

It works perfectly.它完美地工作。 But now, I need to access a particular CGI that cannot be on the SSL virtual host.但是现在,我需要访问无法在 SSL 虚拟主机上的特定 CGI。 So I would like to redirect all request, except the following:所以我想重定向所有请求,除了以下内容:

" http://www.mydomain.com/mycgi/cgi.php " " http://www.mydomain.com/mycgi/cgi.php "

I have search on this forum and found some post concerning regex exclusion, but none is working.我在这个论坛上搜索过,发现了一些关于正则表达式排除的帖子,但没有一个有效。 Any help would be greatly appreciated.任何帮助将不胜感激。

Thanks.谢谢。 Alain阿兰

Apache 2.2 and later has negative lookahead support in regular expressions. Apache 2.2 及更高版本在正则表达式中具有负前瞻支持。 If you are using Apache 2.2 or later this should work:如果您使用的是 Apache 2.2 或更高版本,这应该可以工作:

RedirectMatch ^/(?!mycgi/cgi.php)(.*) https://www.mydomain.com/$1

I believe the RedirectMatch is a short-circuit sorta deal .我相信 RedirectMatch 是一笔短路交易 What this means, is that if you put another RedirectMatch ahead of your match-all, only the first match will execute.这意味着,如果您在全匹配之前放置另一个 RedirectMatch,则只会执行第一个匹配。 so something like...所以像...

RedirectMatch (/mycgi/cgi.php) http://www.mydomain.com$1 
RedirectMatch (.*) https://www.mydomain.com$1 

The previous answers are correct, but what if tomorrow there will be another exception?前面的答案是正确的,但如果明天又出现一个例外呢? You'll get a fat, hard understand regex.你会得到一个胖的,难以理解的正则表达式。 Is better (easier to understand and maintain) to use an If directive expression with Apache internal variables.使用带有 Apache 内部变量的If指令表达式更好(更易于理解和维护)。

<If "%{REQUEST_URI} !~ m#^/mycgi/cgi.php$# && \
     %{REQUEST_URI} !~ m#^/anothercgi/cgi.php$#">
    RedirectPermanent / https://%{HTTP_HOST}/%{REQUEST_URI}
</If>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM