Forcing a Download with Apache and .htaccess

Sometime you don’t want to give your site visitors the option to open a file in their web browser. This could be a Microsoft Office document, or even a giant jpg or png image. When you want to force download a certain file type, simply add something like this to an .htaccess file in the directory that the file(s) are located in:

 ForceType application/octet-stream Header set Content-Disposition attachment  
 ForceType application/octet-stream Header set Content-Disposition attachment 

This particular directive forces downloads all .xls and .eps files (the * means match any file name, followed by the extension of the file) in the same directory, as well as any sub-directories, and ensures that the browser will not try to open the file.

In general, I like to avoid putting such things in my root .htacess file, preferring to create a “downloads” directory of some sort, and just adding the above lines as needed. Some servers are different, so your mileage may vary – check the comments below.

19 thoughts on “Forcing a Download with Apache and .htaccess

  1. For those Expression Engine users out there, this did not work for me until I moved the rules into the .htaccess file in the root.

    Placing an .htaccess file in the folder that contained the images was not effective.

  2. You need to:

    LoadModule headers_module modules/mod_headers.so

    ForceType application/octet-stream

    Header set Content-Disposition attachment

    Works fine.

  3. Actually, you could skip the ForceType part altogether. The Header set Content-Disposition attachment directive already tells the browser to download the file.
    By using ForceType you will also prevent the browser from knowing what kind of file it is (such as application/pdf, application/msword or image/jpeg). It will ensure the client won’t try to display anything, but it’s a bit of an overkill.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>