如何根据URL设置Apache条件标头? [英] How to set Apache conditional header based on URL?

查看:66
本文介绍了如何根据URL设置Apache条件标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据URL设置不同的HTTP标头。在我的特定情况下,我希望特定的URL(例如regex ^ / abc $ )具有与所有其他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.

我正在尝试:

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

我还尝试了其他正则表达式 m#^ / abc $#,则没有错误,但是条件条件不匹配。

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

推荐答案

使用 If 条件来评估正则表达式:

Use If condition like this to evaluate regular expression:

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






编辑: Apache 2.4+以下版本适用于我:


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>

如果您使用的是较旧的Apache,请使用此 mod_rewrite 技巧:

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

这篇关于如何根据URL设置Apache条件标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆