jlh
jlh

Reputation: 4717

Selectively force file download with Apache based on URL parameter

I have an Apache 2.2 running and I am forcing some files to be downloaded using this .htaccess snippet:

<Files *.*>
        ForceType application/octet-stream
        Header set Content-Disposition attachment
</Files>

All the affected files are in one subfolder, so this worked nicely so far. Unfortunately it now turns out that this sometimes causes problems (for example, jplayer doesn't like that). I now need to selectively use default behavior, or forced downloads for these files.

I imagine that it must be somehow possible to choose the behavior with an URL parameter, so that

http://example.com/files/music.mp3

would cause normal behavior (i.e. a browser that can play MP3s would do so and jplayer won't complain), and

http://example.com/files/music.mp3?download=1

would force a download. However I can't figure out how I can use ForceType selectively based on the presence of a parameter. I know it would be easily possible with some PHP, but I want to avoid that if possible.

Thanks for any help!

Upvotes: 3

Views: 6015

Answers (2)

Chris
Chris

Reputation: 46

A similar question has already been answered here:

https://stackoverflow.com/a/7446204/2291963

Reads in the QueryString, and will set it for whatever file extensions you decide to use.

Upvotes: 1

hexalys
hexalys

Reputation: 5257

A rather efficient way to do that, would be to create another folder, called say /download/, with your htaccess snippet in it, and redirect all /download/ file requests to the /file/ folder using this added rewrite rule in the same .htaccess

RewriteEngine on
RewriteRule ^(.*)$ files/$1 [L] 

That way for analytics/logs purpose you can identify downloads separately with good semantics, and call your /files/ normally for html embed use, without any .htaccess performance downside for the /files/ requests, which will not be affected by the .htaccess from the /download/ folder.

Upvotes: 1

Related Questions