Restricting access to WordPress login by IP address

If you have a static IP address, like from your own VPN, it is very easy to increase your security tremendously. Simply restrict all logins to that IP address.

With Apache

Now, let’s say your public IP when logged into your VPN is 123.45.67.89. Simply add this to your .htaccess file:

<files wp-login.php>
  order deny,allow
  deny from all
  Allow from 123.45.67.89
</files>

And that’s it.

With Apache behind Varnish

Now, if you’re behind a reverse proxy like Varnish (like I am), things look a bit more complicated. Since all requests now look as they’re coming from your reverse proxy, the previous solution won’t work.

First, make sure your proxy is setting the X-FORWARDED-FOR header correctly. In Varnish you would have this in your vcl_recv block:

sub vcl_recv {

	[…]

	if (req.restarts == 0) {
		if (req.http.X-Forwarded-For) {
			set req.http.X-Forwarded-For = req.http.X-Forwarded-For + ", " + client.ip;
		} else {
			set req.http.X-Forwarded-For = client.ip;
		}
	}

	[…]
}

Now you can look for that header in your .htaccess file, like this:

<files wp-login.php>
  SetEnvIF X-FORWARDED-FOR "123.45.67.89" AllowIP
  order deny,allow
  deny from all
  Allow from env=AllowIP
</files>

And that’s it.

With Nginx

Update October 17, 2015: I’ve written a new post that not only is a huge improvement over the old method I described here, but also adds much more flexibility. Take a look at the post Restrict access to the WordPress dashboard by IP address in Nginx.

1 Comment

  1. I struggled 2 days to restrict wordpress using nginx behind haproxy

    unfortunately nothing worked, finally downgraded back to apache and it works fine now.

    thanks your article helped me

    Cheer
    Zak

Comments are closed.