Sathish Kumar
Sathish Kumar

Reputation: 13

Nginx Directory Listing - Restrict by IP Address

We have a requirement to allow directory listing from few servers and disallow from other ip addresses and all IP addresses should be able to download all files inside the directory.

Can somebody provide the correct nginx config for the same.

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

If I use the above config, only on 1.1.1.1 IP address can directory list from this server and can file download but from other IP addresses download shows forbidden, due to IP address restriction

Is there a way to overcome this issue, thanks.

Upvotes: 1

Views: 2331

Answers (1)

Shawn C.
Shawn C.

Reputation: 6841

Update

As autoindex doesn't like to use variables or be in if blocks this is my working solution to your problem

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

You can do it with a combo of geo and map directives

geo $geoAutoIndexWhitelist {
    default        0;
    1.1.1.1/24     1;
}

map $geoAutoIndexWhitelist $allowAutoIndex {
    1              off;
    0              on;
}

location / {
    root /downloads;
    autoindex $allowAutoIndex;
}

So what is going on is we are telling the autoindex to get the value from the allowAutoIndex map directive which is, in turn, using the geoAutoIndexWhitelist geo directive to return a value based on IP range.

geoAutoIndexWhitelist by default returns a 0 unless the IP falls within the subnet range then it returns a 1, more ranges can be added but the returned values should be 0 or 1.

allowAutoIndex looks at the geoAutoIndexWhitelist and returns off vs. on based on a 0 or 1 result.

Note this ad hoc and untested but should lead you to a solution.

Upvotes: 1

Related Questions