Search code examples
apachemod-rewriteconfig

Apache config: RewriteRule in <If> block never rewrites


I'm customizing the configuration of Apache httpd (2.4.59). Here is one puzzle:

This rule rewrites matching URIs if unconditional:

RewriteRule ^/abc/.* /myscript.php [L]

But if coded this way, the rule does not rewrite and has no effect on the same URIs:

<If true>
    Header always set Test "executed"
    RewriteRule ^/abc/.* /myscript.php [L]
</If>

The test header is sent, but for URIs matching ^/abc/.*, myscript.php is never executed.

What is going on?

FYI, I'm working on <If> with a real condition, not <If true>. But when I tested <If true>, I realized that the RewriteRule was never going to execute anyway.


Solution

  • Here is a "fix" to the RewriteRule - remove ^ from the pattern:

    <If true>
        Header always set Test "executed"
        RewriteRule /?abc/?.* /myscript.php [L]
    </If>
    

    Explanation

    • I added LogLevel alert rewrite:trace6.
    • The log showed the <If> block was processed last, after every other RewriteRule, including those below the <If> block. The <If> was logged as "[*perdir *If/]"(?)
    • Unlike other rules, the pattern for the rule inside the <If> was applied to the absolute path of the target file for each incoming URL.
    • Therefore using ^, without typing in the absolute path, fails to match.
    • For more precise matching, the pattern inside the <If> could include the absolute path.