Nginx RegEx to match a directory and file
Solution 1
Your attempt doesn't work because of the way that nginx selects a location directive. Blocks using ~ take precedence over those using ^~, so the .php block is being selected for wp-login.php. The best approach is probably to catch this inside the .php block:
location ~ \.php$ {
location ~ ^/wp-login\.php$ {
auth_basic "Access Denied!";
auth_basic_user_file .users;
}
fastcgi_pass unix:/var/run/php-fpm/www.sock;
...
}
Solution 2
One reading your comments on mgorven's answers, i believe this is what you are trying to achieve.
Add this block before your \.php$ matching block.
location ~* ^/wp-admin/$ {
allow 192.168.0.10;
deny all;
include fastcgi_params;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_pass your_back_endphp;
}
location ~* ^/wp-login.php$ {
allow 102.168.0.10;
deny all;
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
include fastcgi_params;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_pass your_back_endphp;
}
With wp-admin you cannot have fastcgi_split_path_info due to this will break styling and js being served.
Related videos on Youtube
timmanna
Updated on September 18, 2022Comments
-
timmanna 10 monthsI'm wondering if it's possible to match Wordpress directory and specific file in the same location, so at the moment I've got rule to match only the wp-admin directory:
## Restricted Access directory location ^~ /wp-admin/ { auth_basic "Access Denied!"; auth_basic_user_file .users; location ~ \.php$ { fastcgi_pass unix:/var/run/php-fpm/www.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } }I would like to also match the
wp-login.phpfile but I can't get to work, I've tried the following:location ^~ /(wp-admin/|wp-login.php) { ... -
timmanna over 10 yearsAhh, I think it's because when I try to access .../wp-admin, Wordpress redirects to .../wp-login.php... and then the Nginx rule is applied. Can you suggest the solution for this? -
mgorven over 10 years@HTF I don't understand what you're trying to achieve? Which rule are you referring to, and what do you want it to do instead? -
timmanna over 10 yearsSorry for misleading, basically I would like to limit access to Wordpress "wp-admin" directory and "wp-login.php" file by IPhttp://wiki.nginx.org/HttpAccessModule#allow. I've configured location block for directory but I'm not sure how to match this login file -
mgorven over 10 years@HTF Add a location block to matchwp-login.phpinside the.phpblock, as I've shown in my example. Put your access control rules inside there (in addition to the location block for the/wp-admin/directory).