Jump to content

Apache2 <If> blocks don't work with regex matches against the %REQUEST_URI variable.


netcarver
 Share

Recommended Posts

Just a heads up, I hope this might save someone some time in the future.

TL:DR> It's taken me hours to work out that Apache version 2.4 <If> statements are broken when trying to do regular expression matches against the %REQUEST_URI variable. Try matching against the variable called %THE_REQUEST instead - but be careful with your regex.

Background: I've been trying to add more relaxed CSP headers for the admin portion of one of my PW sites because my default, strict, CSP headers stop some admin features from working properly. After diving in to Apache2 regexs and conditionals, I thought I had the answer with this...

    <If "%{REQUEST_URI} !~ m#^/admin/?#i">
        # CSP headers for external visitors.
        Header set Content-Security-Policy "<strict policy for public site>"
    </If>
    <Else>
        # CSP headers for admin visitors.
        Header set Content-Security-Policy "<lax policy for admin>"
    </Else>

...but I couldn't make it work. After experimenting for several hours I found that the regex shown above does work if you limit it to a single-character match; which is essentially useless for determining if we are in the admin interface.

However, you can achieve a useful match with the following...

    <If "%{THE_REQUEST} !~ m# /admin/?#i">
        ...
    </If>
    <Else>
        ...
    </Else>

...which checks verses the entire HTTP request line made to the server.

This block can go in your vhosts file or in the site's .htaccess file.

Here's the Apache documentation: https://httpd.apache.org/docs/current/expr.html and it seems I'm not alone in having this issue: https://serverfault.com/questions/940953/apache-if-statement-not-working?noredirect=1&lq=1 although neither of these links had workable solutions for me.

  • Like 8
Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...