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

Muhammad Hassaan
  • 7,296
  • 6
  • 30
  • 50
DonutReply
  • 3,184
  • 6
  • 31
  • 34
  • 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 Jan 09 '12 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. – aaronbauman Nov 24 '14 at 18:13

3 Answers3

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.

Muhammad Hassaan
  • 7,296
  • 6
  • 30
  • 50
TxRegex
  • 2,347
  • 21
  • 20
13

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

Muhammad Hassaan
  • 7,296
  • 6
  • 30
  • 50
Gumbo
  • 643,351
  • 109
  • 780
  • 844
2

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

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358