【问题标题】:Nginx Directory Listing - Restrict by IP AddressNginx 目录列表 - 受 IP 地址限制
【发布时间】:2018-05-19 10:13:39
【问题描述】:

我们要求允许来自少数服务器的目录列表并禁止来自其他 IP 地址,并且所有 IP 地址都应该能够下载目录内的所有文件。

有人可以提供正确的 nginx 配置吗?

location / {
root /downloads;
autoindex on;
allow 1.1.1.1;
deny all;
}

如果我使用上述配置,只有在 1.1.1.1 的 IP 地址上才能从该服务器列出目录并可以下载文件,但由于 IP 地址限制,从其他 IP 地址下载显示被禁止

有没有办法解决这个问题,谢谢。

【问题讨论】:

    标签: nginx nginx-location nginx-config


    【解决方案1】:

    更新

    由于autoindex 不喜欢使用变量或在 if 块中,这是我对您问题的有效解决方案

    geo $geoAutoIndexWhitelist {
        default             0;
        1.1.1.0/24          1;
    }
    
    server {
        ...
        root /downloads;
        autoindex off;
    
        location / {
            if ($geoAutoIndexWhitelist) {
            rewrite ^/(.*)$ /all_downloads/$1 last;
            }
            try_files $uri $uri.html $uri/ =404;
        }
    
        location /all_downloads/ {
            internal;
            alias /downloads;
            autoindex on;
        }
    }
    

    您可以使用geo 和map 指令的组合来实现

    geo $geoAutoIndexWhitelist {
        default        0;
        1.1.1.1/24     1;
    }
    
    map $geoAutoIndexWhitelist $allowAutoIndex {
        1              off;
        0              on;
    }
    
    location / {
        root /downloads;
        autoindex $allowAutoIndex;
    }
    

    所以我们告诉autoindex 从allowAutoIndex map 指令中获取值,这反过来又使用geoAutoIndexWhitelist geo 指令返回一个基于IP 范围。

    geoAutoIndexWhitelist 默认返回 0,除非 IP 在子网范围内,否则返回 1,可以添加更多范围,但返回值应为 0 或 1。

    allowAutoIndex 查看 geoAutoIndexWhitelist 并根据 0 或 1 结果返回关闭与打开。

    请注意此临时且未经测试的内容,但应该会引导您找到解决方案。

    【讨论】:

    • 感谢肖恩的回复和意见。我尝试在我的站点配置中的 nginx.conf 和 location 部分中添加地理和地图部分,但我收到错误 nginx: [emerg] invalid value "$allowAutoIndex" in "autoindex" 指令,它必须是 "on" 或 "off"在 domain.conf 中
    • @Sathish 你是对的。我将我的非工作示例更新为一个工作示例。
    猜你喜欢
    • 1970-01-01
    • 2012-03-05
    • 1970-01-01
    • 2013-12-14
    • 2018-12-26
    • 1970-01-01
    • 1970-01-01
    • 2015-10-21
    • 2010-09-16
    相关资源
    最近更新 更多