Can I make Apache or IIS add a specific header if a certain query string is present?

I want every URL with "download=1" in the query string to be served with Content-Disposition: attachment.

Weird question title because originally this was about Apache only, but now I've added IIS too.


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:

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

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

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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