In Apache, directory listing enables users to see a directory’s contents in the absence of an index file (such as index.html or index.php). Although this could help view public files, it exposes private files and your server’s architecture, which is a security issue.
By turning off directory listing, you can reduce potential vulnerabilities and stop unlawful access to files. Apache provides several methods for disabling it.
Why Disable Directory Listing?
- Prevents exposure of sensitive files (e.g., configuration files, backups).
- Hides folder structure from potential attackers.
- Reduces the risk of misuse through known file paths.
Follow the methods to disable directory listing:
- Using the Virtual Host Configuration
If you are hosting multiple websites through Apache Virtual Hosts, you can disable directory listing for individual sites.- Open the virtual host configuration file from the locations:
- /etc/apache2/sites-available/ (Debian/Ubuntu)
- /etc/httpd/conf.d/ (CentOS/RHEL)
Example:sudo nano /etc/apache2/sites-available/example.conf
- Edit the <VirtualHost> Block:
Add or modify the <Directory> directive with Options -Indexes:<VirtualHost *:80> ServerName example.com DocumentRoot /var/www/html/example <Directory /var/www/html/example> Options -Indexes </Directory> </VirtualHost>
Explanation:
Options -Indexes ? Disables directory listing for the specified directory. - Save and restart Apache
sudo systemctl restart apache2 # Debian/Ubuntu sudo systemctl restart httpd # CentOS/RHEL
- Open the virtual host configuration file from the locations:
- Applying settings globally
To disable directory listing for all websites hosted on Apache:- Locate the Main Apache Configuration File
- Debian/Ubuntu: /etc/apache2/apache2.conf
- CentOS/RHEL: /etc/httpd/conf/httpd.conf
- Edit the <Directory> Section
sudo nano /etc/apache2/apache2.conf # Debian/Ubuntu sudo nano /etc/httpd/conf/httpd.conf # CentOS/RHEL
Add or update:
<Directory /var/www/> Options -Indexes </Directory>
Replace /var/www/ with your web root if different.
- Restart Apache:
sudo systemctl restart apache2 # Debian/Ubuntu sudo systemctl restart httpd # CentOS/RHEL
- Locate the Main Apache Configuration File
- Using .htaccess (Per Directory Control)
If you don’t have root access to Apache’s configuration files, you can disable directory listing using .htaccess in the target directory:Options -Indexes
Note: Ensure ‘AllowOverride’ Options is enabled in Apache’s configuration for .htaccess to work.
In this manner, disabling directory listing is a simple yet effective security solution. Whether you use a basic ‘.htaccess’ file, global Apache configuration, or Virtual Host settings, keeping this ability restricted helps shield your files and server structure from unwelcome exposure.
Best Practice is to keep your Apache security settings current and functional, and review them frequently.
Need to apply your changes? Learn How to restart Apache within WHM