Nginx RegEx to match a directory and file

nginxregex

I'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.php file but I can't get to work, I've tried the following:

location ^~ /(wp-admin/|wp-login.php) {
...

Best Answer

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;
    ...
}