Search code examples
iisdownloadhttp-headers

how to force a download of .mp3 and .mp4 files in IIS


I have a dedicated folder that I use for when a .mp4 file needs downloading (instead of streaming inside a browser window).

This web.config file inside that folder manages to do this for me:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <outboundRules>
                <remove name="Remove Server Response Header" />
                <rule name="Remove Server Response Header" enabled="true">
                    <match serverVariable="RESPONSE_SERVER" pattern=".*" />
                    <conditions />
                    <action type="Rewrite" />
                </rule>
                <rule name="Force Download For MP4s" preCondition="FileIsMP4">
                    <match serverVariable="RESPONSE_Content-Disposition" pattern=".*" />
                    <conditions logicalGrouping="MatchAny">
                        <add input="{REQUEST_FILENAME}" matchType="Pattern" pattern="(.*)\\([^/]+)\.mp4$" ignoreCase="true" negate="false" />
                    </conditions>
                    <action type="Rewrite" value="Value: attachment; filename={C:2}.mp4" />
                </rule>
                <preConditions>
                    <preCondition name="FileIsMP4">
                        <add input="{REQUEST_FILENAME}" pattern="\.mp4$" />
                    </preCondition>
                </preConditions>
            </outboundRules>
        </rewrite>
        <staticContent>
            <remove fileExtension=".mp3" />
            <remove fileExtension=".mp4" />
            <remove fileExtension=".m4v" />
            <remove fileExtension=".avi" />
            <remove fileExtension=".mov" />
            <mimeMap fileExtension=".mov" mimeType="application/octet-stream" />
            <mimeMap fileExtension=".avi" mimeType="application/octet-stream" />
            <mimeMap fileExtension=".m4v" mimeType="application/octet-stream" />
            <mimeMap fileExtension=".mp4" mimeType="application/octet-stream" />
            <mimeMap fileExtension=".mp3" mimeType="application/octet-stream" />
        </staticContent>
    </system.webServer>
</configuration>

How would I go about adding .mp3 files to also download instead of playing?

I tried different things but nothing is working. Sorry, https://en.wikipedia.org/wiki/Regular_expression is not my forte.


Solution

  • As workaround I ended up just using another folder for .mp3 files.