A file that opens in the browser instead of downloading: how to force the download

The short answer: the browser decides for itself what to do with a file: a PDF or an image opens in the window, a ZIP downloads. To force the download there are two ways: the download attribute on the link (simple, for files on the site itself) or a server header (stronger, works for a whole folder).

What the site needs

What What to do
The “download” attribute On the link: <a href="file.pdf" download>. It works for files on the same site; some browsers ignore it for files from another address.
The server header It tells the browser to treat the file as an attachment. It is done in the .htaccess of the folder where the files are.
When to force For files the person wants to keep (templates, forms, installers). For a PDF to read, letting it open is friendlier.
What it does not fix If the PDF “opens blank” or the download fails, that is another problem: The invoice PDF will not download.
Cache After changing the rule, clear the cache: the browser may keep the old behaviour.

Getting started

1 Try the attribute first: add the word “download” to the file’s link and test.
2 If you need to force it for a folder, take a copy of that folder’s .htaccess and add: <FilesMatch "\.(pdf|zip|docx)$">
Header set Content-Disposition attachment
</FilesMatch>
3 Put this rule only in the folder of files to download (for example, /downloads/), not on the whole site.
4 Test the link in a clean browser (private window): the download should appear.
5 If it gave a 500 error after saving, the server did not accept the line: go back to the .htaccess copy and open a ticket: Error 500.
This rule applies to all files of those types in the folder and subfolders. If you put it in the main folder, the site’s PDFs stop opening in the browser. Use a folder just for downloads. And put the file’s type and size on the link, so whoever downloads knows what is coming.
For cache and header rules in general: Browser caching with .htaccess and .htaccess for PHP projects. Public files that should not be there: Files that must never be public.

The file still opens instead of downloading? Open a ticket with the file’s address.

Open a support ticket

SEE ALSO

The invoice PDF will not download, opens blank or looks wrong: what to try

Browser caching with .htaccess

.htaccess for PHP projects: friendly URLs and redirects

Files that must never be public: .git folders, .env, backups and database dumps

Error 500 Internal Server Error: finding the cause, step by step

Clearing the cache: the browser’s, the computer’s, and the site’s

RECOMMENDED PRODUCT

Web hosting with cPanel

Domain and SSL included, daily backups and the panel you already know. from $6.59/mo (3-year plan, with coupon)

See plans
  • 0 Users Found This Useful
Was this answer helpful?