nginxnginx-confignginx-location

How do I force nginx basic authentication for files starting with a certain mask?


I want my nginx instance to switch to basic authentication when serving all files starting with /dev-*.* mask.

For example, if the /dev-phpinfo.php is requested, only a specific user may be able to see its output, after providing a password.

In Apache I can easily set it up with the <Files> directive like this:

  <Files "dev-*.*">
    AuthType Basic
    AuthName "Restricted"
    AuthBasicProvider file
    AuthUserFile "/etc/apache2/.htpasswd"
    AllowOverride All
    Require user webadmin
  </Files>

How do I do that in nginx?

UPDATE: I am not asking for a regexp to achieve this. I am asking about how to integrate it into the location {} block. I am not sure that this can only be achieved with the regexp, so I am asking to a knowhow which might be interested to community.


Solution

  • You are probably use the fastcgi_pass content handler to process the PHP files, something like

    location ~ \.php$ {
        include fastcgi_params;
        ...
        fastcgi_pass /path/to/php-fpm.sock;
    }
    

    You can use the map block to enable basic auth for the certain files as follows:

    map $uri $realm {
        /dev-phpinfo.php  "Restricted access";
        ...
        default           off;
    }
    
    server {
        ...
        location ~ \.php$ {
            auth_basic $realm;
            auth_basic_user_file /path/to/.htpasswd;
            include fastcgi_params;
            ...
            fastcgi_pass /path/to/php-fpm.sock;
        }
    }
    

    To define file masks you can use regular expressions (using PCRE/PCRE2 syntax), e.g. (for the dev-*.php files):

    map $uri $realm {
        "~/dev-.*\.php$"  "Restricted access";
        ...
        default           off;
    }