Rewrite Subfolder to Subdomain in web.config

前端 未结 2 1171
北恋
北恋 2020-12-10 05:59

I\'m attempting to write a rewrite rule for the following scenario.

User attempts to load this picture:

domain.com/images/folder/picture.jpg
<         


        
相关标签:
2条回答
  • 2020-12-10 06:26

    NOTE: Changing the rule to be a redirect instead of a rewrite fixes the problem. Ideally you want it to be a redirect but I have spent many hours trying to get the rewrite to work, and so far no solutions yet.

    <rule name="Rewrite to images.cdn.com" enabled="true" stopProcessing="true">
    <match url="images/(.+)$" ignoreCase="true" />
    <action type="Redirect" url="http://images.cdn.com/{R:1}" />
    </rule>
    
    0 讨论(0)
  • 2020-12-10 06:29

    EDIT:

    To be able to rewrite (and not only redirect) urls to outside websites, you need to install the Application Request Routing module and enable the proxy mode.

    To do so:

    1. Download and install the module
    2. Open your IIS management console (inetmgr)
    3. Select Your server node
    4. Double click on Application Request Routing Cache: ARR
    5. Click on Server Proxy Settings on the Actions pane (right of the screen)
    6. Check the box Enable proxy and click on Apply proxy

    The second step is about setting up your rules.

    If you want your rewrite to be based on the path then use the following code:

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

    Or if you keep the same folder architecture on the second website you can simplify as follow:

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

    If you want to catch only the files ending with a specific extension (let's say images):

    <rewrite>
      <rules>
        <rule name="Forward to cdn domain">
          <match url="^images/folder/.+\.(?:jpg|bmp|gif)$" />
          <action type="Rewrite" url="http://cdn.domain.com/{R:0}" />
        </rule>
      </rules>
    </rewrite>
    

    Please refer to: http://www.iis.net/learn/extensions/url-rewrite-module/iis-url-rewriting-and-aspnet-routing (section "Which Option Should You Use?")

    TIP:

    The best way to test your pattern is to use the IIS test pattern tool.

    At the root of your website -> URL Rewrite -> Create a blank rule -> click on test pattern: Pattern test

    If you don't get the expected result, you can debug your rewrite using the Failed Request Tracing tool

    0 讨论(0)
提交回复
热议问题