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 的访问
这个倒与 WordPress 本身无关了,your-site.com/wp-json,默认是所有人皆可访问。如果你基于服务器负载,或安全等方面考虑选择性输出,可以借助 Nginx 控制访问。先看下面的例子:
- # 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