Using Regular Expressions to Reduce Exposure

The Internet is filled with bots (zombie machines working to the master’s bid), spiders and etc. Recently, I saw a large number of attempts gaining access to my WordPress Login page (and only the wp-login.php, obviously attempts from some scripts). Okay, I believe I have good password and username hygiene which did deterred the bots but then why not prevent non-public addresses from accessing it?

Such configuration I believe can be easily done by .htaccess in Apache, but I’m using nginx and it’s slightly different so here’s my method. nginx allows the user to put rules into config so look into the your nginx configuration.

One way to do this is to do a regular expression matching for the remote IP address ($remote_addr) or if you are like me who puts the Web Server behind a HAProxy, look at the IP address forwarded for ($http_x_forwarded_for). You can generate your IP range using Google IP Address Range Rules (IP regular expression generator). And here is my additional configuration, this is to be inserted below the basic web root config.

location ~ /wp-login.php {
 if ($remote_addr !~ ^(192.168.([0-7]).([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-5])))$ ) { 
  //Only allow my private addresses to have access
  return 403;
 } 

 if ($http_x_forwarded_for != "" ) { 
  //Any proxy-ed access will be denied too
  return 403;
 }

 root html;
 fastcgi_pass unix:/tmp/php-fpm.sock;
 fastcgi_index index.php;
 fastcgi_param SCRIPT_FILENAME /var/www/html/wordpress$fastcgi_script_name;
 include fastcgi_params;
}