Tutorial

How to Force File Download in WordPress

Force file download by adding a small code snippet to an .htaccess file.

Problem

Your visitors click links to text files or image files in the Media Library and the file is rendered directly on the browser. You need that the browser shows a download window asking visitors what to do with the file.

Solution

Follow this procedure to solve the problem described above.

Step 1: Open the upload directory using FTP or cPanel. By default, this directory is at wp-content/uploads.

Step 2: Open the .htaccess file and add the code below. If the file does not exist, create it in the root of the upload directory. Adjust the list of file extensions as required.

# Force file download
<FilesMatch "\.(jpg|jpeg|png|gif|mp3|mp4|mpg|mpeg|avi|txt)$">
	ForceType application/octet-stream
	Header set Content-Disposition attachment
</FilesMatch>
# END

Step 3: Click a link to a file in the Media Library, whose extension is listed in the code. Verify that the browser launches a download window for the file.

Further reading

I recommend the other tutorials in this series to learn more about managing attachments in WordPress.

Source code

The source code developed in this tutorial is available here.

WordPress

Related Tutorials

Open chat
Need help?
Hi! 🤝 Open the chat if you have any question, feedback, or business proposal. I would love to hear from you.