You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WordPress中完全禁用wp-json及相关REST API路由?

解决WordPress拦截/wp-json根端点的问题

你当前的代码仅移除了REST API的具体路由(比如/wp/v2/pages),但/wp-json根端点的响应是由API基础机制生成的,需要额外处理。以下是几种可行方案:

方案一:通过PHP钩子拦截根端点请求

使用rest_request_before_callbacks钩子,检查未登录用户的请求路径,返回禁止访问的错误:

add_action('rest_request_before_callbacks', 'block_rest_api_root', 10, 3);
function block_rest_api_root($response, $handler, $request) {
    if (!is_user_logged_in() && $request->get_route() === '/') {
        return new WP_Error(
            'rest_forbidden',
            'REST API根路径访问被禁止',
            array('status' => 403)
        );
    }
    return $response;
}

将这段代码添加到主题的functions.php文件或自定义插件中即可。

方案二:通过.htaccess拦截(Apache服务器)

如果你的服务器使用Apache,可以在网站根目录的.htaccess文件中添加以下规则,阻止未登录用户访问/wp-json根路径:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_URI} ^/wp-json/?$
RewriteCond %{HTTP_COOKIE} !wordpress_logged_in_[^\=]+\= [NC]
RewriteRule ^ - [R=403,L]
</IfModule>

方案三:完全禁用未登录用户的REST API

如果想彻底禁止未登录用户访问所有REST API路径(包括根路径和所有子路由),可以使用rest_authentication_errors钩子:

add_filter('rest_authentication_errors', 'block_rest_api_for_guests');
function block_rest_api_for_guests($result) {
    if (!is_user_logged_in()) {
        return new WP_Error(
            'rest_unauthorized',
            '你无权访问REST API',
            array('status' => 401)
        );
    }
    return $result;
}

这个方案会让所有未登录用户的API请求都返回401未授权错误,安全性更高。

内容的提问来源于stack exchange,提问作者Naren Verma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 13:02:45