Nginx Block and Redirect IP Access to WordPress wp-admin

This article will show you how to block all IP addresses to a specific folder (wp-admin) and only allow access to your IP address. Additionally, the blocked IP’s will be redirected to a location that you choose. This is a fantastic way to lock down your WordPress installation with minimal effort and maximum results.

How to block all access and redirect IP’s to wp-admin in Nginx

To get started, open up your Nginx site configuration file and add the following lines of code:

location ~ ^(wp-admin|wp-login\.php) {
try_files $uri $uri/ /index.php?$args;
index index.html index.htm index.php;
	allow x.x.x.x;
	deny all;
	error_page 403 = @wp_admin_ban;
}

location @wp_admin_ban {
	rewrite ^(.*) http://mywebsite.com permanent;
}

This will only allow access to the IP you specify (i.e. x.x.x.x) and redirect all other IP’s to mywebsite.com.

Allow multiple IP’s access to wp-admin in Nginx

If you would like to allow access for multiple IP addresses to your wp-admin folder, this can be done by adding a another allow x.x.x.x; directive in your Nginx site configuration file:

location ~ ^(wp-admin|wp-login\.php) {
try_files $uri $uri/ /index.php?$args;
index index.html index.htm index.php;
	allow x.x.x.x; # First IP to allow access
	allow x.x.x.x; # Second IP to allow access
	allow x.x.x.x; # Third IP to allow access
	deny all;
	error_page 403 = @wp_admin_ban;
}

location @wp_admin_ban {
	rewrite ^(.*) http://mywebsite.com permanent;
}