1 Jul

How to force file downloading with htaccess

Nearly every browser will show image oder video files you want to provide for download in the browser itself instead of opening a download dialog.

Most of the websites suggest to use this code in your .htaccess:

<FilesMatch "\.(jpg|zip|avi)$" >
	ForceType application/octet-stream
</FilesMatch>

But this is not enough! Even when the MIME-Type is set to “octet-stream”, some browsers will still open the files their selfs because they have detected the .jpg or .avi file extension.

The solution to this is to add the following header:

<FilesMatch "\.(jpg|zip|avi)$" >
	ForceType application/octet-stream
	Header add Content-Disposition "attachment"
</FilesMatch>

With this header every browser i tested opened a download dialog, regardless of which file extension is present.

To use this, your webserver has to have mod_headers activated (It is most likely already included in Apache, but not activated): Apache Module mod_headers

20 thoughts on “How to force file downloading with htaccess

  1. I used the below one for force PDF download. I am using Apache 2.2.17. But I got an internal server error (500).

    ForceType application/octet-stream
    Header add Content-Disposition “attachment”

    Can anyone help me regarding this.

  2. Hi,

    it didn’t work first time i tried, then i cleared the browser cache and it worked. This is a very good solution.
    It would be interesting, if it works with IE. Im using FF on Mac OSX

    Thanks for sharing this.

  3. Which browsers require the 2nd line, ‘Header add Content-Disposition “attachment”‘ for the automatic file download prompt to work? If it’s IE7 and below, then to heck with them. 🙂 Thanks for the code!

  4. Thanks for your response. I just tested with a site of mine, and the whole site gives me a 404 error unless I remove that 2nd line. The “force download” works with that line removed (I’m using FF 18.0). Any thoughts why it works better without that 2nd line?

  5. the only things coming to my head are: clear browser cache, make sure that the copied text does not consist of malicious chars, check if this interferes with your own config.

    other than that i have no idea what is happening. try it without the 2nd line, but test it in every browser to be sure…

Leave a Reply to Mamun Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.