Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

regex - How to set Apache conditional header based on URL?

I want to set 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 rest.

I am trying 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 doesn't 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 to work?

I also tried the alternate regex form m#^/abc$# and then there is no error but there is no match for the If condition.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use If condition like this to evaluate regular expression:

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

EDIT: On Apache 2.4+ following works for me:

<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>

If you are on older Apache then use this mod_rewrite trick:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...