Force Download in WordPress for PDF files

This was actually rocket science. Or it felt like it. It should have been quick and simple. Took me a bit more than I would like to admit.

So we had a WordPress site with a lot of downloadable PDFs. One of the PDFs was being weird. When you clicked on it, it would attempt to view in the browser but only got 50% of the way through and just stopped.

Sounded like a corrupt file, right? It wasn’t. If you downloaded the file, it was fine to open. Accounting asked if we could force the file to download instead. I said sure. Easy enough. I’ve done it before but it’s been awhile.

I wanted to stay away from a massive WP theme update. It was on an older site that got very specific traffic that required a password to download. I found this chunk of code in several StackOverflow posts about updating the .htaccess file:

<FilesMatch "\.(?i:pdf)$">
    # Force File Download
    ForceType application/octet-stream
    Header set Content-Disposition attachment
</FilesMatch>

Looks harmless right? When I saved it, I got a 500 Internal Server Error. Always fun. So after quickly commenting out the new lines and doing some googling, I found out I needed a tiny apache update. thanks to Stack. I needed to run sudo a2enmod headers to enable an apache setting. Then do a restart after that of course.

Viola. Uncommented the htaccess code and worked like a charm.

Hope this helps someone.