rest_allowed_cors_headers
云策文档标注
概述
rest_allowed_cors_headers 是一个 WordPress 过滤器,用于控制 REST API CORS 请求中允许的请求头列表。它允许开发者自定义哪些头信息可以传递给 REST API,默认包括用于文件上传的 Content-* 头以及用于身份验证的 Authorization 和 Nonce 头。
关键要点
- 过滤器名称:rest_allowed_cors_headers
- 参数:$allow_headers(字符串数组,允许的请求头列表)和 $request(WP_REST_Request 对象,当前请求上下文)
- 默认允许的头:Content-* 头(用于媒体端点文件上传)、Authorization 和 Nonce 头(用于身份验证)
- 用途:通过 add_filter 钩子修改允许的 CORS 头,例如移除特定头以增强安全性或调整 API 行为
- 版本历史:在 WordPress 5.5.0 中引入,6.3.0 版本添加了 $request 参数
代码示例
add_filter( 'rest_allowed_cors_headers', 'wpdocs_block_specific_headers');
function wpse213123_block_specific_headers( $allow_headers, $request ) {
// Check for a specific header item in the list
if ( in_array( 'Content-Type', $allow_headers ) ) {
unset( 'Content-Type' );
}
return $allow_headers;
}注意事项
使用此过滤器时,需确保正确处理 $allow_headers 数组,避免破坏默认功能;在 WordPress 6.3.0 及以上版本中,$request 参数可用,提供更多上下文信息。
原文内容
Filters the list of request headers that are allowed for REST API CORS requests.
Description
The allowed headers are passed to the browser to specify which headers can be passed to the REST API. By default, we allow the Content-* headers needed to upload files to the media endpoints.
As well as the Authorization and Nonce headers for allowing authentication.
Parameters
$allow_headersstring[]-
The list of request headers to allow.
$requestWP_REST_Request-
The request in context.
Source
$allow_headers = apply_filters( 'rest_allowed_cors_headers', $allow_headers, $request );
Skip to note 2 content
LumberHack
You can remove specific headers using a snippet like the one below
add_filter( 'rest_allowed_cors_headers', 'wpdocs_block_specific_headers'); function wpse213123_block_specific_headers( $allow_headers, $request ) { // Check for a specific header item in the list if ( in_array( 'Content-Type', $allow_headers ) ) { unset( 'Content-Type' ); } return $allow_headers; }