Password protecting files in a folder in Nginx using .htpasswd

╄→гoц情女王★ 提交于 2019-12-08 03:27:57

问题


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.



来源:https://stackoverflow.com/questions/37902392/password-protecting-files-in-a-folder-in-nginx-using-htpasswd

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!