Make Apache or IIS add a header if a certain query string is present

mod_rewrite with mod_headers make this possible as follows:

RewriteEngine on
RewriteCond %{QUERY_STRING} (^|&)download=1(&|$)
RewriteRule ^(.*?([^/]*))$ $1 [E=DOWNLOAD:$2]
Header set "Content-Disposition" "attachment; filename=\"%{DOWNLOAD}e\"" env=DOWNLOAD

Haven't tested this with anything containing non-ASCII or spaces. Those will probably end up showing in the file name URL-escaped, i.e. "%20" etc.
Edit: Special characters should work just fine.


I had to do the same on IIS 7.5, so here's the way to do it: place the following XML into a site's <system.webServer><rewrite> ... section:

<outboundRules>
    <rule name="DownloadAnything">
        <match serverVariable="RESPONSE_Content_Disposition" pattern=".*" />
        <action type="Rewrite" value="attachment" />
        <conditions>
            <add input="{QUERY_STRING}" pattern="(^|&amp;)download=1(&amp;|$)" />
        </conditions>
    </rule>
</outboundRules>

(obviously if you already have an <outboundRules> element, place only the rule inside the existing element)