22 Votes

HTACCESS: Force Download of specific File Types

Tutorial by Stefan Trost | Last update on 2023-01-18 | Created on 2014-09-16

Depending on the browser settings, some file types such as images, videos, music, text files or PDF documents are always displayed directly in the browser window. This is a problem whenever you would like to offer for example a JPG or PDF file as a download: each time when clicking on the corresponding link, the download is not starting and the file is just displayed instead.

In this tutorial, I would therefore like to show you two solutions with which you can prevent the display of any file types in the browser, so that a user is always offered the corresponding files as a download regardless of his browser settings. One solution works with the help of HTACCESS, the other with PHP.

The HTACCESS Solution

In order to force the download of certain file types respectively files with a certain file extension with the help of HTACCESS, we only need a few lines in our HTACCESS file.

You can just add the following four lines that are sufficient for our purpose:

<FilesMatch "\.(?i:pdf|jpg|gif|avi|mp3)$">
  ForceType application/octet-stream
  Header set Content-Disposition attachment

The trick is to declare the files as binary attachments, whereby the browser offers the files for download instead of displaying them by default.

In the first line, all the file extensions are listed for which this should apply. In our example, we declared all files with the ending PDF, JPG, PNG, AVI and MP3 as binary attachments.  Of course, you can change the list of extensions to your own needs as desired.

Furthermore, with using "?i:" we ensure that the lowercase or uppercase writings of the file extension does not matter (PDF and pdf).

The PHP Solution

Of course, this is a very simple method. We are more flexible when we work with PHP. If you want to have more control over your downloads, I recommend the PHP download script for files.

This script also offers the possibility to force the browser to a file download, but you have more possibilities than only changing the header (for example the implementation of a download counter or downloading under another name than the name with which the file is stored on the server).


About the Author

AvatarYou can find Software by Stefan Trost on sttmedia.com. Do you need an individual software solution according to your needs? - sttmedia.com/contact
Show Profile


Related Topics

PHP: File Download Script

Tutorial | 0 Comments

Rename File to its Folder Name

Tutorial | 0 Comments

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.


Ask your own question or write your own article on askingbox.com. That’s how it’s done.