通过 IP 保护位置,同时在其他地方应用基本身份验证

scr*_*ler 4 nginx whitelist http-basic-authentication

我想达到以下结果:

  • 将基本身份验证应用于任何位置、文件、路径
  • 删除 IP/CIDR 范围白名单的基本身份验证
  • 阻止所有人访问特定目录及其下的所有内容,除了一个 IP 地址(包括以上内容)

这是我正在使用的 nginx 配置:

server {
    listen 80 default;

    # Basic auth
    auth_basic "Restricted";
    auth_basic_user_file /etc/nginx/.htpasswd;

    satisfy any;
    # IP whitelist
    include /etc/nginx/conf.d/ip-whitelist.conf.include;
    deny all;

    # Lock down the "hello" directory to specific IP addresses
    location /hello/ {
        # Developers only - ever!
        allow 12.34.56.78;
        deny all;
    }
    # ...
}
Run Code Online (Sandbox Code Playgroud)

目前发生的事情是上面项目符号列表中的第 1 点和第 2 点正在工作 - 即白名单中的任何 IP 都没有跨站点的基本身份验证,但如果 IP 未列入白名单,则会提示他们进行基本身份验证。

然而,“hello”的位置块似乎不起作用,并且仍然允许“hello”目录下的任何内容具有与上述相同的条件,例如,如果我尝试/hello/world.php从列入白名单的 IP访问,它会被提供。如果我从非白名单 IP 访问它,我将获得基本身份验证。

我想阻止 IP 以外的所有人访问“hello”目录12.34.56.78(示例)。

我需要改变什么?

小智 8

正如您所发现的,不建议只使用服务器级别的身份验证设置,因为它们将适用于所有位置。虽然可以关闭基本身份验证,但似乎没有办法清除现有的 IP 白名单。

更好的解决方案是将身份验证添加到该/位置,以便它不会被/hello.

如果您有其他需要基本身份验证和 IP 白名单的位置,问题就会出现,在这种情况下,可能值得考虑将身份验证组件移动到包含文件或将它们嵌套在/.

server {
    listen 80 default;

    # Lock down the "root" directory to specific IP addresses
    location / {
        satisfy any;

        # Basic auth
        auth_basic "Restricted";
        auth_basic_user_file /etc/nginx/.htpasswd;

        # IP whitelist
        include /etc/nginx/conf.d/ip-whitelist.conf.include;
        deny all;

        # Inherits auth settings from parent
        location ~ \.php$ {
            # PHP specific config
        }
    }

    # Lock down the "hello" directory to specific IP addresses
    location /hello/ {
        # Developers only - ever!
        allow 12.34.56.78;
        deny all;
    }
    # ...
}
Run Code Online (Sandbox Code Playgroud)