Reputation: 155
I'm trying to usa a regex
which only matches string which doesn't start with some other string. As far as I know and from some other questions here on Stack Overflow I should use a negative look-ahead assertion. But for some reason it doesn't seem to work. Consider the following three strings:
/match.jpg
match.png
excludedpath/no-match.gif
I want my regex pattern to only match the first two strings, because the last string starts with excludepath/
. What I have tried is the following:
(?!excludedpath\/)(.*)\.(gif|jpg|png)$
I want to use this regex pattern in a rewrite rule for Apache. Basically I want to simply load all images (with those three extensions) unless they are in the format of http://example.com/excludedpath/some-image.jpg
:
RewriteCond %{REQUEST_FILENAME} (?!excludedpath\/)(.*)\.(gif|jpg|png)$
RewriteRule ^(.*)$ $1 [L]
RewriteCond "/my/path/to/application/%{REQUEST_URI}" !-f
RewriteRule ^(.*)$ /index.php/$1 [L]
Anybody can tell me why it still matches all three strings: This Link and how to fix it?
Upvotes: 0
Views: 826
Reputation: 44259
It's because you don't require the lookahead to look at the beginning of your string. Just add another anchor:
^(?!excludedpath\/)(.*)\.(gif|jpg|png)$
Otherwise, the engine will of course fail to match at the first character (because the lookahead kicks in), but then it will gladly try to match from the second character. And of course xcludedpath...
does not set off the negative lookahead.
Since your rubular example has the last string start with a slash, you could add an optional slash to the lookahead, if you want to exclude both variants:
^(?!\/?excludedpath\/)(.*)\.(gif|jpg|png)$
Upvotes: 2