使用.htpasswd密码保护Nginx文件夹中的文件 [英] Password protecting files in a folder in Nginx using .htpasswd

查看:110
本文介绍了使用.htpasswd密码保护Nginx文件夹中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用.htpasswd保护我域中的/admin/部分.

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

我可以使用以下配置成功保护根index.php文件:

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

但是该文件夹中的关联文件仍然可见.例如,在 http://domain.com/admin/whatever.php 上-该页面加载后,会显示Nginx密码身份验证,但是您可以简单地取消它并仍然查看页面.

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.

经过研究,我尝试使用 regex通配符失败.

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

不起作用:

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

无效:

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

如何密码保护根索引以及所有子文件夹和文件? /admin/之后的所有内容都将无法访问.

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

推荐答案

您的正则表达式语法几乎不错,实际上您必须将两次尝试混合使用:

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.

这是正则表达式的基础之一,所以我建议您进一步了解它们. 学习正则表达式包含有关下一步操作的指南.它还包含有关处理换行符时.通配符的一些限制的注释,尽管这不适用于URL.

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.

这篇关于使用.htpasswd密码保护Nginx文件夹中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆