Here is a quick .htaccess snippet that will force files to download instead of displaying in the browser. This method works for any site running on an Apache server.
By default, PDF documents, text files, and other types of files are displayed in the browser instead of being downloaded to the user’s local machine. The reason for this is the default MIME type set by Apache, which instructs the browser to display instead of download. Fortunately, the default MIME type can be changed by adding the following line in your site’s root .htaccess file:
AddType application/octet-stream pdf
This will change the behavior of the file so it is downloaded instead of displayed in the browser. You can change the file type from PDF to whatever by editing the
AddType application/octet-stream pdf txt doc
Here we have added three extensions,
doc. So when this code is added to the root .htaccess, PDF, TXT, and DOC files will be downloaded instead of displayed.
Getting more specific
If you need to force download for a specific file (instead of all files of a type), you can use Apache’s
<Files> directive, like so:
<Files magazine.pdf> AddType application/octet-stream pdf </Files>
This will match only files named
magazine.pdf in any directory and force them to download. To match only files contained in a specific directory, simply move the code to the .htaccess file located in that directory. If the desired directory does not contain an .htaccess file, you can create one.
Multiple file types
Here is another similar example that shows how to force download for multiple file types, plus sends an additional header to make it all good.
<FilesMatch "\.(mov|mp3|jpg|pdf)$"> ForceType application/octet-stream Header set Content-Disposition attachment </FilesMatch>
Here we are matching any file that has an extension of
FilesMatch. If the current file matches one of the extensions in the list, it will be sent as an
application/octet-stream via the
ForceType directive. Additionally, we send along a header that sets the
Content-Disposition as an attachment.