How to redirect user to 404 page not found error when non admin try to access wp-admin or wp-login.php

.htaccess, wordpress

Solution

I use this snippet to redirect people away from the backend if they're not already logged in. You could modify it to point to your 404:

// BLOCK BACKEND ACCESS FOR NON-ADMINS
add_action( 'init', 'blockusers_init' );
function blockusers_init() {
    // If accessing the admin panel and not an admin
    if ( is_admin() && !current_user_can('level_10') ) {
        // Redirect to the homepage
        wp_redirect( home_url() );
        exit;
    }
}

Just change the URL from the `home_url()` function to your 404 page under `wp_redirect`.

Problem

For security reasons I am trying to restrict my wordpress site admin and login panel access to non-admin users by rewriting the link, such that if user types in http://www.mysite.com/wp-login.php or http://www.mysite.com/wp-admin he is redirected to Error 404 page but if he types http://www.mysite.com/blah-login or http://www.mysite.com/blah-admin is redirected to my WP admin or login panel. I have following options to do that. - Rewrite .htaccess file which I am not good at and don't wanna mess up my site's .htaccess file. Use $wp_rewrite class which I did by writing a small plugin, its code is given below. ``` register_activation_hook( __FILE__, 'activate' ); function activate() { rewrite(); flush_rewrite_rules(); } register_deactivation_hook( __FILE__, 'deactivate' ); function deactivate() { flush_rewrite_rules(); } add_action( 'init', 'rewrite' ); function rewrite() { add_rewrite_rule( 'blah-admin/?$', 'wp-admin', 'top' ); add_rewrite_rule( 'blah-login/?$', 'wp-login.php', 'top' ); add_rewrite_rule( 'blah-register/?$', 'wp-register.php', 'top' ); } ``` It works perfectly only problem is it does not restrict access to wp-admin, wp-login.php or wp-registe.php (Which is must). I can write following rule to a new .htaccess file. ``` AuthUserFile /dev/null AuthGroupFile /dev/null AuthName "Wordpress Admin Access Control" AuthType Basic <LIMIT GET> order deny,allow deny from all allow from xxx.xxx.xxx.xxx </LIMIT> ``` and place it under wp-admin folder, it has 2 drawbacks one is it will only restrict access to my wp-admin folder not wp-register.php or wp-login.php and second is I am a DHCP client so `allow from xxx.xxx.xxx.xxx` will not work for me. I could use a combination 2nd and third rule but it will definitely not work because I cannot provide an alternative permalink to a overall blocked folder. As for a last resort I could use wp-modal plugin's permalink rewriting capability, it works like a charm but this plugin is not compatible with my theme. So is there really a solution to my problem?

Original source