Just because you host something online does not necessarily mean that you want everyone to have access to it. For example, if you are developing or hosting an online project which contains private information sitting on your filesystem available only for authorized access only. In this tutorial, you will see how to deny direct download to a file by using an .htaccess
configuration file on an Apache web server in Linux.
In this tutorial you will learn:
- How to use
.htaccess
to deny access to file - How to add
AllowOverride All
setting to Apache virtual host

Category | Requirements, Conventions or Software Version Used |
---|---|
System | Any Linux distro |
Software | Apache web server |
Other | Privileged access to your Linux system as root or via the sudo command. |
Conventions |
# – requires given linux commands to be executed with root privileges either directly as a root user or by use of sudo command$ – requires given linux commands to be executed as a regular non-privileged user |
Deny Direct File Download With .htaccess
Keep in mind that this method will deny direct access to a file via URL, but does not totally secure the file from prying eyes. Other methods should be employed for protecting data with sensitive content.
- The first thing we will do is create a directory where our private data will be placed. The default directory for an Apache website is
/var/www
on most systems, so we will put the directory inside there.$ sudo mkdir /var/www/data
- Use nano or your preferred text editor to create the
.htaccess
file inside this directory.$ sudo nano /var/www/data/.htaccess
- Inside of the
.htaccess
file, paste the following content. If you want to name a specific file instead of using a wildcard, you can edit the code below accordingly. Save your changes to the file and exit when done.<FilesMatch ".*"> Order Allow,Deny Deny from All </FilesMatch>
- Next, you will need to add the
AllowOverride All
setting to your Apache site’s virtual host configuration file. This file should be located inside of the/etc/apache2/sites-enabled
directory. Open the appropriate file and add the setting below.<Directory /var/www/data> AllowOverride All </Directory>
As seen above, you will need to add this option to the corresponding
Directory
directive. - Restart Apache for the changes to take effect.
Debian based: $ sudo systemctl restart apache2 Red Hat based: $ sudo systemctl restart httpd
- Navigate to your website’s private directory – which in this example is
http://localhost/data
– and you should be presented with a 403 forbidden error.
Closing Thoughts
In this tutorial, we saw how to deny direct download to a file in an Apache web server on a Linux system. This can be done through the .htaccess
configuration file, but only works if the proper setting is present inside of the site’s virtual host file.