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

瀏覽器相容性

另見