5

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.

7

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)

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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