I have the following .htaccess
file on my Apache Server, which does not work
<If "%{HTTP_HOST} == 'www.example.com'">
RewriteCond %{REMOTE_ADDR} !^192.168.8.8$
RewriteRule .* - [F]
RewriteRule ^([A-Za-z0-9_-]+)$ index.php?p=$1 [NC,L]
</If>
The code works fine without the if-Statement.
But with the if Statement
RewriteRule ^([A-Za-z0-9_-]+)$ index.php?p=$1 [NC,L]
does not work. It throws a "404 Not Found error"
2
Answers
I came myself to the following solutiuon. which i really like.
The "problem" is because the mod_rewrite directives are embedded inside an
<If>
expression.<If>
blocks are merged very late, after the request has been mapped back to the file system. In this context, theRewriteRule
pattern matches against the absolute filesystem path, not a relative URL-path, so the second rule above will not match as expected.So, the rule would need to be rewritten like this instead:
Or, more simply, remove the start-of-string anchor – although this does make the match somewhat ambiguous:
Or, preferably, avoid the
<If>
construct altogether as you can get unexpected conflicts with other directives (outside of the<If>
construct). For example:(The
NC
flag is not necessary in the 2nd rule, since you are already matchingA-Z
anda-z
in the regex. ALso, use^
instead of.*
in the first rule, since you don’t need to actually match anything here.)If you have many such rules that apply to just this one host then you can reverse the logic and skip the N rules that follow when the requested host is not what is expected. For example: