I’m trying to understand mod_rewrite better and have one particular problem I think I need to get my head round first.
I am rewriting http://www.somesite.tld/a/b/c to index.php?path=a/b/c using the following
RewriteRule ^(?!index.php)(.*)$ index.php?path=$1 [NC,L]
An equivalent rewrite would, in this case, be
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?path=$1 [NC,L]
- This does not work without the
RewriteCond— path=index.php would be the result without specifically ignoring files or saying ‘not index.php’. Why is this? - Also, what is the
?!and?:syntax that I sometimes see used? I do not understand the use of the?when it is not prefixed by anything. - And why, in the first RewriteRule above, do the second pair of brackets return a match for $1?
Cheers
(?= ...)and(?! ...)is special syntax in Perl regular expressions and in PCRE, which is the regex library that Apache uses. They are, respectively, positive and negative lookahead assertions: they match an empty string if the text after it matches or does not match the content in the brackets.They are non-capturing, so they don’t define any
$n(it would be pointless, since they match an empty string).(?: ...)is also non-capturing, it is used to group subexpressions.Your first rule should work in
.htaccess(but not in a virtual host configuration file), though it would be more correct to write it asPerhaps another rule is interacting with it. You can check what exactly is being matched and rewritten with
RewriteLogandRewriteLogLevel.