Content-Security-Policy: base-uri 指令

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2020 年 1 月⁩ 起,所有主流浏览器均已支持。

HTTP Content-Security-Policybase-uri 指令限制了可在文档的 <base> 元素中使用的 URL。如果此值不存在,则允许任何 URI。如果此指令不存在,用户代理将使用 <base> 元素中的值。

CSP 版本 2
指令类型 文档指令
default-src 回退 否。不设置此项允许任何 URL。

语法

http
Content-Security-Policy: base-uri 'none';
Content-Security-Policy: base-uri <source-expression-list>;

此指令可以具有以下值之一

'none'

不能使用 <base> 元素设置基本 URI。单引号是强制性的。

<source-expression-list>

以空格分隔的源表达式值列表。如果 <base> 元素的值与给定的任何源表达式匹配,则可以设置基本 URI。对于此指令,以下源表达式值适用

示例

Meta 标签配置

html
<meta http-equiv="Content-Security-Policy" content="base-uri 'self'" />

Apache 配置

apacheconf
<IfModule mod_headers.c>
Header set Content-Security-Policy "base-uri 'self'";
</IfModule>

Nginx 配置

nginx
add_header Content-Security-Policy "base-uri 'self';"

违规案例

由于您的域不是 example.com,因此 href 设置为 https://example.com<base> 元素将导致 CSP 违规。

html
<meta http-equiv="Content-Security-Policy" content="base-uri 'self'" />
<base href="https://example.com/" />

<!--
// Error: Refused to set the document's base URI to 'https://example.com/'
// because it violates the following Content Security Policy
// directive: "base-uri 'self'"
-->

规范

规范
内容安全策略级别 3
# directive-base-uri

浏览器兼容性

另见