How to set Apache conditional header based on URL?

后端 未结 2 382
一个人的身影
一个人的身影 2020-12-19 03:49

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 th

相关标签:
2条回答
  • 2020-12-19 04:09

    This is a one-line alternative taken from documentation:

    Header always set CustomHeader my-value "expr=%{REQUEST_URI} =~ m#^/special_path.php$#"
    
    0 讨论(0)
  • 2020-12-19 04:14

    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
    
    0 讨论(0)
提交回复
热议问题