Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mod Rewrite Regex Negative Lookahead

I am trying to match all URIs that begin with #/tool_[a-z\-]+# except if it's followed by /public. Such as /tool_calculator or whatever.

For example, if the URI begins with /tool_store-front or /tool_store-front/anything-but-public then I want to redirect them to HTTPS. So, /tool_store-front/public would not redirect.

Here's what I have and it's not working

RewriteCond %{HTTPS} =off
RewriteCond %{REQUEST_URI} ^/?tool_[a-z-]+(?!/public.+) [OR]
RewriteCond %{REQUEST_URI} ^/?secure
RewriteCond %{REQUEST_URI} !^/?secure/public/info
RewriteRule ^(.*)$ https://www.example.org%{REQUEST_URI} [NC,L]
like image 564
Yes Barry Avatar asked Mar 31 '17 20:03

Yes Barry


1 Answers

You can also change your negative lookahead condition to this using a possessive quantifier:

RewriteCond %{HTTPS} =off
RewriteCond %{REQUEST_URI} ^/tool_[a-z-]++(?!/public) [NC,OR]
RewriteCond %{REQUEST_URI} ^/secure(?!/public/info) [NC]
RewriteRule ^ https://www.example.org%{REQUEST_URI} [NE,R=301,L]

You can also use this negative lookahead:

RewriteCond %{REQUEST_URI} ^/tool_[a-z-]+(?!.*/public) [NC,OR]

Problem in your condition ^/?tool_[a-z-]+(?!/public.+) is that regex engine is backtracking [a-z]+, one position before / to assert negative lookahead (?!/public.+) true.

like image 170
anubhava Avatar answered Sep 21 '22 07:09

anubhava