How to set URL-based Apache conditional header?

I want to set a different HTTP header depending on the url. In my particular case, I want a specific URL (e.g. regex ^/abc$) to have a different header than all the others.

I am trying to do this:

<IfModule mod_headers.c>
    <If "%{REQUEST_URI} =~ /^\/abc$/">
        Header set Content-Security-Policy: "default-src 'none'; style-src 'self' 'unsafe-inline';"
    </If>
    <Else>
        Header set Content-Security-Policy: "default-src 'none'; child-src https: *.youtube.com 'self'; connect-src 'self'; font-src 'self'; img-src 'self'; script-src https: *.ytimg.com *.youtube.com 'self'; style-src 'self';"
    </Else>
</IfModule>

However, this does not seem to work, the log says:

Cannot parse condition clause: Failed to compile regular expression

What am I doing wrong and how can I make this work?

I also tried an alternative form of regular expression m#^/abc$#, and then there is no error, but there is no match for the If condition.

+4
source share
1 answer

If, , :

<If "%{REQUEST_URI} =~ m#^/abc/?$#">

EDIT: Apache 2.4+ :

<IfModule mod_headers.c>
    <If "%{THE_REQUEST} =~ m#\s/+abc/?[?\s]#">
        Header set Content-Security-Policy: "default-src 'none'; style-src 'self' 'unsafe-inline';"
    </If>
    <Else>
        Header set Content-Security-Policy: "default-src 'none'; child-src https: *.youtube.com 'self'; connect-src 'self'; font-src 'self'; img-src 'self'; script-src https: *.ytimg.com *.youtube.com 'self'; style-src 'self';"
    </Else>
</IfModule>

Apache, mod_rewrite:

RewriteEngine On

RewriteCond %{THE_REQUEST} \s/+abc/?[\s?] [NC]
RewriteRule ^ - [E=MYENV1:1]

RewriteCond %{THE_REQUEST} !\s/+abc/?[\s?] [NC]
RewriteRule ^ - [E=MYENV2:1]

Header set Content-Security-Policy "default-src 'none'; style-src 'self' 'unsafe-inline';" env=MYENV1
Header set Content-Security-Policy "default-src 'none'; child-src https: *.youtube.com 'self'; connect-src 'self'; font-src 'self'; img-src 'self'; script-src https: *.ytimg.com *.youtube.com 'self'; style-src 'self';" env=MYENV2
+2

Source: https://habr.com/ru/post/1672279/


All Articles