.htaccess file allows you to modify Apache server configuration without actually modifying its config files. Let us take a look at how to deny access to directory using .htaccess in Apache web server.
How to Deny Access to Directory Using .htaccess
Here are the steps to deny access to directory using .htaccess. Before you proceed, please enable .htaccess (mod_rewrite) in Apache web server. Here are the steps to do it on:
1. Open .htaccess file
Open .htaccess in a text editor. It is typically located at /var/www/html. If not, you can simply create a blank file with filename – .htaccess
Remember to put a dot (.) before filename.
$ sudo vim /var/www/html/.htaccess
2. Deny Access to Directory
Let’s say you want to block access to /includes/ folder, then you can do that with RedirectMatch statement.
RedirectMatch 403 ^/includes/?$
This will only block the directory but not the files and subdirectories in it. If you want to block them too, then use .* instead of ? as shown below
RedirectMatch 403 ^/folder/.*$
You can also place an .htaccess file in the folder that you want to deny access to and add the following lines to it.
Deny from all
Disable Directory Listing
If you only want to disable directory listing then add the following line to your .htaccess file.
3. Restart Apache web server
Restart Apache web server to apply changes
$ sudo /etc/init.d/apache2 start [Debian or Ubuntu] # sudo apachectl restart [RHEL, CentOS or Fedora]