Regex - how to match everything except a particular pattern
Asked Answered
C

3

6

I'm using Apache and I want to redirect all received request to the ssl virtual host.

So I have the following line in the regular http virtual host:

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

which basicaly replace $1 by everything.

It works perfectly. But now, I need to access a particular CGI that cannot be on the SSL virtual host. So I would like to redirect all request, except the following:

"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

Carcinoma answered 26/4, 2010 at 20:18 Comment(0)
S
3

Apache 2.2 and later has negative lookahead support in regular expressions. If you are using Apache 2.2 or later this should work:

RedirectMatch ^/(?!mycgi/cgi.php)(.*) https://www.mydomain.com/$1
Succinic answered 26/4, 2010 at 20:52 Comment(1)
Thank you very much. It works perfectly. You resolved in less then 30 minutes what I was working on for almost 8 hours now!Carcinoma
S
1

I believe the RedirectMatch is a short-circuit sorta deal. What this means, is that if you put another RedirectMatch ahead of your match-all, only the first match will execute. so something like...

RedirectMatch (/mycgi/cgi.php) http://www.mydomain.com$1 
RedirectMatch (.*) https://www.mydomain.com$1 
Scissure answered 26/4, 2010 at 20:35 Comment(3)
+1 You beat me by a few seconds. Your first rule should redirect to 'http' and you might want to add a leading '/' to it as well.Eer
Won't that first rule result in a redirect loop?Succinic
Wow... it was fast!!! But unfortunately by putting this line in my "normal non SSL" virtual host, it does not work. Firefox give me that error: Firefox has detected that the server is redirecting the request for this address in a way that will never complete. And I think this is normal because we ask Apache to do a redirect. So Apache receive the request, match it against the first regex then redirect to himself, match again, and so on. Your idea about that? I tryed to place the line in my SSL virtual server but it is ignored. AlainCarcinoma
H
0

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.

<If "%{REQUEST_URI} !~ m#^/mycgi/cgi.php$# && \
     %{REQUEST_URI} !~ m#^/anothercgi/cgi.php$#">
    RedirectPermanent / https://%{HTTP_HOST}/%{REQUEST_URI}
</If>
Hayner answered 1/11, 2019 at 14:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.