Blocking admin access
-
Just need some advice on the best way to do the following:
In the folder wp-admin/ you can add an htaccess file to:
– Blocks admin access
– Allow admin access from specific IPs,
– Always allow access to wp-admin/admin-ajax.php and login CSS files for the frontend## Block Admin Acess. Allow from IPs order deny,allow allow from 2.123.215.199 allow from x.x.x.x deny from all ## Allow access to wp-admin/admin-ajax.php <Files admin-ajax.php> Order allow,deny Allow from all Satisfy any </Files> ## Allow default login CSS to enqueue <Files ~ ".(css)$> Order allow,deny Allow from all Satisfy any </Files>What would you say is the best way to acheive the exact same results above, but with PHP?
I’m not the best with code, but I’ve come up with this solution, and it works. If you notice any problems with this or have anything to add, please let me know:function kp_admin_forbidden_access() { // array of IPs to allow admin access $allowips = array( "2.217.219.78", "999.899.193", "90.196.226.221" ); // to allow admin-ajax.php and login CSS files to load on frontend, we need to end the execution of the this function unless on an admin page. Not sure the best way to do this. // wp-admin/admin.php is only included when on an admin page, so check if this file is included, otherwise end execution of this function. $included_files = get_included_files(); if(!in_array(ABSPATH . 'wp-admin/admin.php', $included_files) ) return; // if remote IP address doesn't match allowed IPs, forbid access if(!in_array($_SERVER['REMOTE_ADDR'], $allowips) ) { header('HTTP/1.0 403 Forbidden'); header('Content-Type: text/html; charset=utf-8'); echo 'Forbidden'; die(); } } add_action( 'admin_init', 'kp_admin_forbidden_access' );
The topic ‘Blocking admin access’ is closed to new replies.