Disabling Directory Listing on Nginx Server

The directory listing feature on Nginx is controlled by the ngx_http_index_module. Directory listing is disabled by default on the Nginx configuration file. However, it is possible to disable directory listing if it was enabled because of a regression or configuration changes.

The Nginx parameter, autoindex, is used together with the location segment to enable or disable the directory listing feature.

How Can We Disable It?

The default configuration file of a Nginx server is called nginx.conf and can be found in /usr/local/nginx/conf, /etc/nginx or /usr/local/etc/nginx. If the default value has been changed, you can see a setting similar to the following:

server {
listen   80;
server_name  domain.com www.domain.com;
access_log  /var/...........................;
root   /path/to/root;
location / {
index  index.php index.html index.htm;
}
 location /somedir {
autoindex on;
}
}

In this section, the determinant parameter is autoindex on; as we mentioned above. In the above example, the directory listing is configured only for the somedir directory. If no directory is specified (e.g. location / {autoindex on;}), the rule will be applied to all the folders. To disable directory listing, we need to switch the value of the autoindex to off. Do not forget to run the below command in order for changes to go into effect:

service nginx restart