WordPress4.7以上版本如何禁用JSON REST API?

WordPress国产主题推荐

WordPress 4.7 以上的版本建议使用 rest_enabled 并不能完全禁用 REST API,而是应该换用 rest_authentication_errors 过滤器来限制访问。在 wp-json 页面有如下提示:

自 4.7.0 版本起,已不建议使用 rest_enabled,请换用 rest_authentication_errors。 REST API 不再能被完全禁用,不过您可以用“rest_authentication_errors”过滤器来限制对该 API 的访问。

所以想要在 WordPress 4.7 以上版本完全禁用 wp-json 功能(JSON REST API),只需要将以下代码添加到当前主题的 functions.php 文件中即可:

//完全禁用 wp-json
function disable_rest_api( $access ) {
return new WP_Error( '无访问权限', 'Soooooryyyy', array(
'status' => 403
) );
}
add_filter( 'rest_authentication_errors', 'disable_rest_api' );
//移除 wp-json 链接
remove_action ( 'wp_head', 'rest_output_link_wp_head', 10 );

以上内容整理自@智慧宫

另外,我们也可以借助Nginx控制/wp-json的访问,具体如下:

# https://devework.com/wordpress-rest-api-dynamic-output.html
location /wp-json {
if ($http_user_agent !~ '(iPhone|Android)'){
return 403;
}
try_files $uri $uri/ /index.php?$args;
}

如果你熟悉 Nginx 语法,就知道上面的代码实现了:除了 iOS 跟 Android 设备(通过判断请求头的 UA 信息),其它访问 /wp-json 的路径均返回 403 状态码。这在一定程度上起到了保护作用。

以上内容整理自@DeveWork

2024年5月15日更新:WordPress完全禁用REST API(最新版)

将以下代码添加到当前主题的functions.php文件中并保存更新文件即可。

/**
* WordPress 完全禁用 REST API(最新版)- 龙笑天下
* https://www.ilxtx.com/disable-json-rest-api-in-wordpress.html
*/
// 屏蔽 REST API
if ( version_compare( get_bloginfo( 'version' ), '4.7', '>=' ) ) {
function lxtx_disable_rest_api( $access ) {
return new WP_Error( 'rest_api_cannot_acess', '无访问权限', array( 'status' => rest_authorization_required_code() ) );
}
add_filter( 'rest_authentication_errors', 'lxtx_disable_rest_api' );
} else {
// Filters for WP-API version 1.x
add_filter( 'json_enabled', '__return_false' );
add_filter( 'json_jsonp_enabled', '__return_false' );
// Filters for WP-API version 2.x
add_filter( 'rest_enabled', '__return_false' );
add_filter( 'rest_jsonp_enabled', '__return_false' );
}
// 移除头部 wp-json 标签和 HTTP header 中的 link
remove_action('template_redirect', 'rest_output_link_header', 11 );
remove_action('wp_head', 'rest_output_link_wp_head', 10 );
remove_action('xmlrpc_rsd_apis', 'rest_output_rsd');

以上内容整理自@龙笑天下

WordPress的REST API是否被禁用,测试方法很简单,只需要在在网站首页网址后面添加“wp-json”并访问,即可看到具体结果。

文章创作不易,期待您的评分

本文地址:https://boke112.com/article/p5001.html

版权声明:本文内容来源于互联网资源,由 boke112百科 整理汇总!发布此文是出于传递更多信息之目的,若有来源标注错误或侵犯了您的合法权益,请联系我们,确认后马上更正或删除,谢谢!
wu