Force Files to Download (instead of opening in the browser) using .htaccess

Apache server LogoRunning a self hosted website can be one of the hardest task if you’re not a web developer and are not familiar with the coding languages and the way things work in the server environment. Sometimes as a webmaster you want your users to be able to easily download the file off your servers instead of the files getting opened up within the browser in a separate tab or window. This can be because there’s a file which needs to be edited in the full version of the program or sometimes the unsupported files by the browser end up opening within the browser with no way to understand it. Whatever the reason be, here’s the way to make the files download using a simple .htaccess command.

.htaccess command to force the files to download

If you are not familiar with .htaccess and hearing it for the first time, here’s some info. If your website is running on a linux/apache based shared web server, your web server is sure to support the .htaccess file. That said, this will not work for windows based servers as the architecture and commands are all different for windows. Enough of into, follow the procedure below to set the files to download.

  1. Check if the folder containing your files already has a .htaccess file or not. If using cPanel, you will be needed to check the check-box to show hidden files. If there exists one, open it for editing. Otherwise create a new file with the name .htaccess in that particular directory and open it for editing.
  2. Depending on whether you are editing the existing file or creating a new one, paste the following code towards the top of the file. You can choose other location if the top includes some more important commands.
    <FilesMatch "\.(?i:doc|odf|pdf|rtf|txt)$">
      Header set Content-Disposition attachment
    </FilesMatch>
  3. Now you need to configure the above command to make sure the extension of your particular file is included in it. For example if you want to force a verisign.cer file to always download, the code will change to the one shown below. As a note, you need to remove the extensions of the files which you want to not to be always downloaded and let the browser choose what to do.
    <filesmatch "\.(?i:doc|odf|pdf|cer|txt)$">
      Header set Content-Disposition attachment
    </FilesMatch>

    We have removed the extension called rtf and replace it with cer. But it’s not important to remove the existing ones. You can add a new extension as |ext in the command.

  4. Save the file when you are done editing/configuring.
  5. Clear your cache and try the direct links to the files of that particular extension. They’ll download instead of opening in the browser.
P.S: The module mod_headers should be loaded in Apache2 for this to work, but don’t worry most web hosts keep it enabled already.

, , , ,

No comments yet.

Leave a Reply