Search code examples
asp.net-coreweb-configurl-rewrite-moduleasp.net-core-2.0iis-10

.Net Core / IIS web config rewrite rules


In my situation I have two domains:

domain.com
domain1.com

where domain1.com is the alias of domain.com

For domain1.com I want to allow only traffic for the urls starting with api/ and redirect all other traffic to domain.com with 301 status code.

i.e. I want to allow requests like domain1.com/api/products/list on the other hand I want to redirect domain1.com/products/list to domain.com

Can anyone please guide how to achieve this with web.config?


Solution

  • Following URL redirect rule should work.

    <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
        <system.webServer>
            <rewrite>
                <rules>
                    <rule name="Domain1">
                        <match url="^(.+)" />
                        <conditions>
                            <add input="{HTTP_URL}" pattern="^/api/(.+)" negate="true" /> 
                        </conditions>
                        <action type="Redirect" url="http://domain/{R:1}" redirectType="Permanent" appendQueryString="true" />
                    </rule>
                </rules>
            </rewrite>
        </system.webServer>
    </configuration>
    

    Quick explanation.

    • We capture the whole incoming URL with match pattern for back-reference for the redirect if needed.
    • And in conditions we negate the API URLs pattern, hence the rule is applied to the URLs not containing /api.
    • The redirect action takes the captured back-reference and appends it to the domain.

    Notes.

    • You might need to adjust slashes in the rule, I assume there will always be a slash after /api.
    • Browsers heavily cache permanent redirects, make sure to use a new Incognito/Private session each time you modify the rule.