Search code examples
iisazureurl-rewrite-moduleazure-cdn

Using IIS Url Rewrite Module To Point To Azure CDN


I have the Url Rewrite Module installed on my web server that is running Windows Server 2012 R2 at a URL like: http://staging.mysite.net/

I have images, fonts, scripts, etc. loaded into the Azure CDN.

I have specified the following rules in my Web.config:

<rewrite>
    <rules>
        <rule name="CDN: fonts" stopProcessing="true">
            <match url="^fonts/(.*)" />
            <action type="Rewrite" url="http://cdn.staging.mysite.net/fonts/{R:1}" appendQueryString="true" />
        </rule>
        <rule name="CDN: images" stopProcessing="true">
            <match url="^images/(.*)" />
            <action type="Rewrite" url="http://cdn.staging.mysite.net/images/{R:1}" appendQueryString="true" />
        </rule>
        <rule name="CDN: pdf" stopProcessing="true">
            <match url="^pdf/(.*)" />
            <action type="Rewrite" url="http://cdn.staging.mysite.net/pdf/{R:1}" appendQueryString="true" />
        </rule>
        <rule name="CDN: scripts" stopProcessing="true">
            <match url="^scripts/(.*)" />
            <action type="Rewrite" url="http://cdn.staging.mysite.net/scripts/{R:1}" appendQueryString="true" />
        </rule>
        <rule name="CDN: style" stopProcessing="true">
            <match url="^style/(.*)" />
            <action type="Rewrite" url="http://cdn.staging.mysite.net/style/{R:1}" appendQueryString="true" />
        </rule>
    </rules>
</rewrite>

Everything is being returned as a 404 error even though the files exist. For example, my page has a reference to /images/en-us/logo.png. I verified that http://cdn.staging.mysite.net/images/en-us/logo.png actually exists.

In addition, the "Test Pattern" function of the Url Rewrite snap in shows that {R1} returns en-us/logo.png when you enter in either images/en-us/logo.png or /images/en-us/logo.png into the "Input data to test" field.

I momentarily had tried using type="Redirect" instead of type="Rewrite" but this causes a duplicate request/response from the server. The first being a 301, the second being a 200. I would like only the 200 response.

++ Obviously, mysite.net is not really my domain and is being used for example purposes only.


Solution

  • I'm using the following rule to rewrite all requests for everything under my /assets folder which works:

    <rewrite>
      <rules>
        <rule name="Rewrite to CDN">
          <match url="^assets/(.+)$" />
          <action type="Rewrite" url="http://cdn.domain.com/{R:0}" />
        </rule>
       </rules>
    </rewrite>