Limit WordPress login by IP with Nginx

Introduction

This quick how-to guide will show you how to limit WordPress login by IP address with Nginx. It will allow you to login to your WordPress site while keeping attackers and bots out. I’ve been using this method for years and it has worked well for me so hopefully it will help you out!

Note: I’m using this on Debian Stretch with PHP 7.3 (here’s how to install PHP 7.3 on Debian Stretch) so if you’re using a different version of PHP make sure your “fastcgi_pass” socket path reflects that in this code.

The Nginx code to block WordPress login by IP address

You’ll want to add this code to your WordPress website’s Nginx .conf file above the code which passes off php files to php-fpm. You also need to change the “x.x.x.x” to your IP address in the below code so if for example your IP was 68.68.68.68 then it would look like “68.68.68.68/32”

# Block access to WordPress login by IP

location ~ /wp-login\.php {
allow x.x.x.x/32;
deny all;
fastcgi_pass unix:/run/php/php7.3-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}

Make sure you put the code above the code that passes php files off to php-fpm so a real world example would look like this:

# Block access to WordPress login by IP
location ~ /wp-login\.php {
allow x.x.x.x/32;
deny all;
fastcgi_pass unix:/run/php/php7.3-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}

# Pass off all php files to PHP-FPM
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/run/php/php7.3-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
fastcgi_intercept_errors on;
fastcgi_ignore_client_abort off;
fastcgi_buffers 256 16k;
fastcgi_buffer_size 128k;
fastcgi_busy_buffers_size 256k;
fastcgi_temp_file_write_size 256k;
}

After you have added the code, make sure it’s correct with this Nginx command:

sudo nginx -t

and then restart Nginx with

sudo systemctl restart nginx

Completion

Hopefully by the end of this quick how-to you should now have your WordPress login page protected by IP address! If you have any trouble or can’t get it to work, please leave a comment below or contact me privately and I will do my best to help you out.

Image Credit: The featured image for this post was created using a photograph by shotinraww on Unsplash.

Leave a Reply

Your email address will not be published. Required fields are marked *