This article explains enabling or disabling the Nginx directory listing on Ubuntu 24.04.
When directory listing is enabled, users can view the contents of a directory, including file names and structure. Disabling directory listing helps prevent users from quickly browsing directories on your server, which can deter potential attackers or intruders from finding exploitable files.
Without a directory listing, users who navigate to a directory without an index file (like index.html or index.php) will get a 403 Forbidden error instead of a list of files.
Disable directory listing
The Nginx global configuration file is located at this path: /etc/nginx/nginx.conf
.
You will find a line in this file dealing with directory listing. Directory listing is enabled by default.
Run the command below to open the global configuration file.
sudo nano /etc/nginx/nginx.conf
The http {} block with the ‘autoindex‘ option enables or disables directory listing in Nginx globally.
http {
##
# Basic Settings
##
sendfile on;
tcp_nopush on;
types_hash_max_size 2048;
# server_tokens off;
autoindex on;
....
}
Remove or add the ‘autoindex on;‘ line in the configuration to enable directory listing globally.
If you want to disable the directory listing for all content in Nginx, change the block above to the one below.
http {
##
# Basic Settings
##
sendfile on;
tcp_nopush on;
types_hash_max_size 2048;
# server_tokens off;
autoindex off;
....
}
Save the exit the file.
Restart Nginx to apply your changes.
Add the ‘autoindex on;‘ to re-enable the directory listing.
Disable directory listing selectively
You can selectively disable directory listing in individual website configuration files if you do not want to change Nginx’s global configuration file.
For example, here’s a basic configuration for a website that disables directory listing.
server {
listen 80 default_server;
listen [::]:80 default_server;
root /var/www/html;
index index.html index.htm index.nginx-debian.html;
server_name _;
location / {
autoindex off;
try_files $uri $uri/ =404;
}
}
This configuration only impacts the /var/www/html/ website in Nginx’s directory.
That should do it!
Conclusion:
- Enabling directory listing allows users to see directory contents, which may be useful for public access.
- Disabling directory listing enhances security by preventing unauthorized exploration of files.
- The global setting in Nginx can easily be adjusted in the nginx.conf file.
- Selective configuration in individual website files provides flexibility in managing directory listing.
- Always remember to restart Nginx after making changes to apply the new settings.
Leave a Reply Cancel reply