17

I've got this this rule in my htaccess file to force linked files to download rather than open in the browser:

<FilesMatch "\.(gif|jpe?g|png)$">
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</FilesMatch>

Is there a way to alter the RegExp so it only applies to files in a certain directory?

Thanks

2
  • 5
    Why are you using application/octet-stream? This is simply telling the browser you don't know what the filetype is. And that's not true. To force a download, Content-Disposition: attachment is all you need.
    – TRiG
    Commented Jan 9, 2012 at 10:08
  • This is not entirely true. Internet Explorer will not always respect Content-Disposition. To force IE to offer the download prompt, it's best to use application/octet-sream. Commented Nov 24, 2014 at 18:13

3 Answers 3

14

Like @gumbo said, put the .htaccess file in the highest level folder you want to affect. and those settings will trickle down to sub folders. You may also want to make sure the headers module is enabled before using this in your htaccess file. The following line will generate an error if the headers module is not enabled:

Header set Content-Disposition attachment

here's an example that forces download of mp3 files only if the headers module is enabled:

<IfModule mod_headers.c>
    <FilesMatch "\.(mp3|MP3)$">
        ForceType audio/mpeg
        Header set Content-Disposition "attachment"
        Allow from all
    </FilesMatch>
</IfModule>

Note: it does not enable the module, it just ignores anything inside the IfModule tags if the module is not enabled.

To enable apache modules you'll either need to edit your httpd.conf file or in wamp server you can click the wamp tray icon and select "Apache -> Apache Modules -> headers_module" or make sure it is checked.

1
  • what will the changes for apache tomcat v8.0? Commented Jan 16, 2015 at 2:58
13

You will probably need to put the directives in the .htaccess file in the particular directory.

1
  • 6
    A ha! Yes! This must be the solution, damn my inflexible mind!
    – DonutReply
    Commented Oct 20, 2010 at 13:47
2

Put it in a <Location> directive, and/or modify the regex to exclude slashes or as appropriate.

1
  • Location doesn't seems to work in htaccess files, is there an alternative way?
    – DonutReply
    Commented Oct 20, 2010 at 13:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.