-->

Password protecting files in a folder in Nginx usi

2019-05-30 23:33发布

问题:

I'm trying to use .htpasswd to protect an /admin/ section on my domain.

I'm able to successfully protect the root index.php file using this config:

    location /admin/ {
            try_files $uri $uri/ =404;
            auth_basic "Restricted";
            auth_basic_user_file /etc/nginx/.htpasswd;
    }

But the associated files within that folder are still viewable. For instance, on http://domain.com/admin/whatever.php -- the page loads, then the Nginx password auth comes up, but you can simply cancel out of it and still view the page.

After doing some research, I've tried to use regex wildcards unsuccessfully.

Doesn't work:

    location "~^/admin/.$" {
            try_files $uri $uri/ =404;
            auth_basic "Restricted";
            auth_basic_user_file /etc/nginx/.htpasswd;
    }

Doesn't work:

    location "~^/admin/*\$" {
            try_files $uri $uri/ =404;
            auth_basic "Restricted";
            auth_basic_user_file /etc/nginx/.htpasswd;
    }

How can I password protect both the root index, and any sub folders and files as well? Everything past /admin/ should be inaccessible.

回答1:

Your regular expression syntax is almost good, you actually have to mix the two tries you made:

location "~^/admin/.*" {
        try_files $uri $uri/ =404;
        auth_basic "Restricted";
        auth_basic_user_file /etc/nginx/.htpasswd;
}

This is because in regular expression syntax . means any character (single one), and * means any amount (which can be zero) of the previous "something". Mixing the two (.*) will mean any amount of any characters.

This is one of the basics of regular expressions, so I'd advise you to learn a bit more about them. Learning Regular Expressions contains guides on what your next steps might be. It also contains notes on some limitations on the . wildcard when dealing with newlines, although that does not apply to URLs.