I have a VPS where I provide pdf files for download.
By default, the pdf files open in the browser when the visitor clicks the download link.
This is not a good practice because if the file is a large one and the visitor has a slow connection, the browser freezes until the entire file is loaded onto it.
Force download of pdf files
To force the files to be downloaded and not open in the browser, the following commands have to be entered.
(i) Enable the mod_headers module with the command
a2enmod headers
(ii) Add the following code to the .conf file of the site
nano /etc/apache2/sites-available/name-of-site.com.conf
The conf file looks like this:
< Directory /var/www/html/ name-of-site.com/public_html > Require all granted < / Directory>ServerName name-of-site.com ServerAlias www. name-of-site.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html/ name-of-site /public_html ErrorLog /var/www/html/ name-of-site /logs/error.log CustomLog /var/www/html/ name-of-site /logs/access.log combined < /VirtualHost>
Add the following within the VirtualHost block
< FilesMatch "\.(pdf|jpg)$"> Header set Content-Disposition attachment < /FilesMatch>
If the code is added after the virtualhost block, it has no effect.
Restart Apache
/etc/init.d/apache2 restart
Now, if you click on the download link, the pdf file will not open in the browser but a download box will be available.
Note: In the above write-up, spacing had to be added because it was otherwise not showing up on the screen. When copying the code, remove the spacing. e.g. “< / Directory>” should be used by closing the spacing.