Sometimes you may need to force your website users to download a file instead of opening them in web browsers. This is especially required if your website hosts a lot of downloadable content. In this article, we will look at how to force download in Apache server.
How to Force Download in Apache
Here are the steps to force download in Apache server. Please enable mod_rewrite(.htaccess) on your Apache server before you proceed further.
1. Open .htaccess file
Open terminal and run the following command to open .htaccess file on for your website.
$ sudo vi /var/www/html/.htaccess
2. Force Download in Apache
Let us say you want to force download for all .pdf files on your website. In this case, add the following lines to your .htaccess file.
<FilesMatch "\.pdf$"> ForceType application/octet-stream Header set Content-Disposition attachment </FilesMatch>
In the above code, FilesMatch tag matches requests which end with .pdf, that is, for pdf files. It applies ForceType directive to all matching requests, which forces download in Apache server. We also set its Content-Disposition header to be attachment for this purpose.
You may also use Files tag instead of FilesMatch above.
<Files ~ "\.pdf$">> ForceType application/octet-stream Header set Content-Disposition attachment </Files>
Both Files & FilesMatch do the same thing but FilesMatch is preferred because it is more intuitive and has simpler syntax.
If you want to force download for multiple files types such as .pdf, .mp3, .avi, you may use regular expressions as shown below in bold. In the following example we use regex operator ‘|’ to imply ‘pdf or mp3 or avi’.
<FilesMatch "\.(pdf|mp3|avi)$"> ForceType application/octet-stream Header set Content-Disposition attachment </FilesMatch>
Please note, if you place the above code in .htaccess file in your website root, then it will be applicable to all URLs on your website.
Sometimes you may want to force download only for files in a specific directory/subfolder. In such cases, create/open .htaccess file in that folder and place the above code in it. If you place it in .htaccess file in a specific folder (/uploads) then forcible downloads will be applicable to only URLs pointing to that folder and its subfolders.
3. Restart Apache Server
Restart Apache Server to apply changes.
$ sudo service apache2 restart
As you can see, it is very easy to force download of files in your website, using Apache server directives. It is very useful to make your website users download files instead of viewing them on their browsers, especially in case of zip files, binaries and executables that may not make sense if opened in browser.
How to Check Commands Executed by User in Linux
How to View User Login History in Linux
How to Send Email in Python
How to Restrict SSH Access to Specific IP Address