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

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

问题描述

我想根据 URL 设置不同的 HTTP 标头.在我的特定情况下,我希望特定的 URL(例如正则表达式 ^/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$# 然后没有错误但没有匹配 If 条件.

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天全站免登陆