How to Disable Directory Browsing on Apache?

02-02-2024 02:12:42

Directory browsing in Apache refers to the scenario where, in the absence of an index file in a directory, Apache by default displays a list of all files in that directory. Enabling directory browsing in a production environment is not recommended as it can lead to the disclosure of website information and increase the attack surface of the website. This guide explains how to disable Apache's directory browsing on an Ubuntu 20.04 cloud server.

Creating a Test Directory

Remotely log into the cloud server and create a test directory in the root directory of the website.

$ sudo mkdir /var/www/html/test

Create two subdirectories and two files in the test directory.

$ sudo mkdir /var/www/html/test/sub-directory_1
$ sudo mkdir /var/www/html/test/sub-directory_2
$ sudo touch /var/www/html/test/file1.txt
$ sudo touch /var/www/html/test/file2.txt

Open a browser and visit: http://www.example.com/test. Replace example.com with the actual domain name or IP address. If directory browsing is enabled, you should be able to see the subdirectories and files you just created.

Disabling Directory Browsing

Open the Apache configuration file, modifying the file path as necessary.

$ sudo nano /etc/apache2/apache2.conf

Locate the following code.

<Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
</Directory>

Adjust the line containing 'Options' to the following code.

<Directory /var/www/>
        Options -Indexes +FollowSymLinks
        AllowOverride None
        Require all granted
</Directory>

The 'Indexes' directive instructs Apache to display a complete list of files in a directory when there is no index file. By adding a minus sign before the 'Indexes' directive, this function of Apache is disabled.

Save the configuration file and restart Apache to apply the changes.

$ sudo systemctl restart apache2

Open the browser again and visit: http://www.example.com/test. This time, a 'forbidden' page should appear, indicating that directory browsing has been successfully disabled. Disabling directory browsing is a crucial step in fortifying a web server.