Nginx目录列表IP限制配置:允许所有IP下载仅指定IP列目录
Solution to Nginx Directory List Access Restriction with Universal File Download
Got it, let's fix this issue for you. The problem with your current configuration is that the allow 1.1.1.1; deny all; rules apply to all requests under /—both directory listings and file downloads. That's why non-allowed IPs can't even download files. We need to split the rules so directory listings are restricted to specific IPs, while file downloads stay open to everyone.
Here's the corrected Nginx configuration:
# Handle all file requests: allow everyone to download files location / { root /downloads; allow all; } # Handle directory requests (paths ending with /): restrict listing to specified IPs location ~ ^/.*/$ { root /downloads; autoindex on; # Add all your trusted server IPs here allow 1.1.1.1; allow 2.2.2.2; # Example of a second allowed IP deny all; }
How this works:
- The first
location /block matches all requests by default. It lets every IP access and download files stored in/downloads. - The second
location ~ ^/.*/$is a regular expression that specifically targets requests for directories (paths ending with a/). For these requests:autoindex onenables directory listing.- We explicitly allow your trusted IPs, then deny all others—so only those specified IPs can view the directory structure.
- Nginx prioritizes regular expression locations over prefix locations, so directory requests will hit the second block, while file requests go to the first.
Testing the configuration:
- Run
nginx -tto validate the config syntax. - Reload Nginx with
systemctl reload nginx(orservice nginx reloaddepending on your OS) to apply changes. - Test from an allowed IP: You should see the directory listing when accessing a folder, and be able to download files.
- Test from a non-allowed IP: Accessing a folder will return a 403 Forbidden, but accessing a specific file (e.g.,
http://your-domain/file.zip) will download normally.
内容的提问来源于stack exchange,提问作者Sathish Kumar
相关产品推荐
相关产品推荐

