WordPress Code Snippets

A fresh mix of code snippets and tutorials

Force file download with .htaccess

224

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 pdf to match whichever extension is desired. Multiple file types may be specified like so:

AddType application/octet-stream pdf txt doc

Here we have added three extensions, pdf, txt, and 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.

Learn more

.htaccess made easy


Show Support

Like our new Facebook Page to show support!