Force file download in IIS7

Kevin Brydon picture Kevin Brydon · Oct 16, 2013 · Viewed 7.9k times · Source

Using IIS7, is there a way to force a clients browser to download a file rather than attempt to display it in-browser? In my case I want to force browsers to download all MP4 video files.

Answer

Kevin Brydon picture Kevin Brydon · Oct 16, 2013

I found the answer from this blog.

Using the IIS7 Url Rewrite module you can change the Content-Disposition header that will suggest the clients browser should download rather than attempt to display the file.

Using IIS Manager (mp4 as an example)

  1. Ensure you have enabled the URL Rewrite module for IIS7
  2. Open IIS7 Manager
  3. Navigate to the site (or sub site) you want to force downloads from
  4. In the Features View select Url Rewrite
  5. In the right hand column select "View Preconditions"
  6. Add the following precondition
    1. Name: FileIsMP4
    2. Using: Regular Expressions
    3. Logical Grouping: Match All
    4. Contition input: {REQUEST_FILENAME}
    5. Check if input string: Matches the pattern
    6. Pattern: \.mp4$
  7. Go back to the URL Rewrite list of rules and add the following outbound rule
    1. Name: Force Download For MP4s
    2. Precondition: FileIsMP4
    3. Match - Matching scope: Server Variable
    4. Match - Variable name: RESPONSE_Content-Disposition
    5. Match - Variable value: Matches the Pattern
    6. Match - Using: Regular Expressions
    7. Match - Pattern: .*
    8. Match - Ignore Case - yes
    9. Conditions - Logical grouping: Match All
    10. Conditions - Input: {REQUEST_FILENAME}
    11. Conditions - Type: Matches the Pattern
    12. Conditions - Pattern: (.*)\\([^/]+)\.mp4$
    13. Conditions - Track capture groups across conditions: yes
    14. Action - Action type: Rewrite
    15. Action - Action Properties - Value: attachment; filename={C:2}.mp4
    16. Action - Replace existing server variable value: yes
    17. Action - Stop processing of subsequent rules: no

Modify Web.Config

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        ...
        <rewrite>
            <outboundRules>
                <rule name="Forcing Download for MP4s" preCondition="FileIsMP4">
                    <match serverVariable="RESPONSE_Content-Disposition" pattern=".*" />
                    <conditions>
                        <add input="{REQUEST_FILENAME}" pattern="(.*)\\([^/]+)\.mp4$" />
                    </conditions>
                    <action type="Rewrite" value="attachment; filename={C:2}.mp4" />
                </rule>
                <preConditions>
                    <preCondition name="FileIsMP4">
                        <add input="{REQUEST_FILENAME}" pattern="\.mp4$" />
                    </preCondition>
                </preConditions>
            </outboundRules>
        </rewrite>
        ...
    </system.webServer>
</configuration>