Preface
WordPress can restrict or block visitors from accessing specific directories, such as the user directory page (https://domain/user). When a visitor accesses a specific directory page, they will be automatically redirected to the site homepage. This can be achieved by adding code to the template function file (functions.php).
Usage
Go to WordPress Dashboard > Appearance > Theme File Editor > click "Template Functions (functions.php) > paste the following code into the template function file > finally click “Update File”
Code
// Block visitors from accessing the /user directory page
function restrict_user_access() {
if (strpos($_SERVER['REQUEST_URI'], '/user') !== false && !current_user_can('administrator')) {
wp_redirect(home_url());
exit;
}
}
add_action('init', 'restrict_user_access');