Tuesday, July 2, 2019

Creating an IIS Redirect Rule from Subdomain to the Root Domain

IIS Rewrite Rules have a lot of inherent complexity.  They use regular expressions and are difficult to debug.  The server variables have little documentation provided by Microsoft.  Recently we had an ask from the business to redirect any requests for subdomains to the main domain.  While this is simple to understand it is difficult to write.

Before you create and debug a rewrite rule you need a couple things:
1.  Install IIS by going into Programs and Features then Windows Features
2.  Install the Web Platform Installer https://www.microsoft.com/web/downloads/platform.aspx  This installs modules for IIS like NuGet installs packages for .NET
3.  Use the Web Platform Installer to install the Rewrite Module

Here is the end result:



Match URL
The thing that hung me up for most of the time was the match url.  This is not the full URL as you would expect but simply the page that was requested like default.aspx.  This is Mistake #1 from Lex Li:  https://blog.lextudio.com/the-very-common-mistakes-when-using-iis-url-rewrite-module-a2ab7e4fee59

Condition Order
In order to do back references to conditions (see the {C:2} and {C:3} variables) you have to put the negate false conditions first.  If you don't the back reference does not work.

HTTP_HOST Matching
If you do not put the regular expression carat ^ for start and the dollar $ sign for end, IIS will redirect until the URL is too long and it throws an error.

Putting It All Together
https://www. - We always want to redirect to secure www
{C:2} and {C:3} - This is a back reference to the last condition, the last set of parenthesis.
{R:1} - This is the requested page from the Match URL

Debugging the Redirect Rule

1.  Here is some excellent documentation how to create a simple test file to debug your rewrite rule:

2.  I used Expresso to debug the regular expression to match the subdomain.rootdomain.  You can also use IIS by double clicking on the Re-write module for the site.    http://www.ultrapico.com/expresso.htm  

3.  What I found to be very useful was to change the redirect url to a query string to see what the variables were.  
<action type="Redirect" url="http://www.somesitethatdoesnotexist.com/?{C:2}-{R:1}" appendQueryString="false" />


Here is the reference documentation from Microsoft:
https://docs.microsoft.com/en-us/iis/extensions/url-rewrite-module/url-rewrite-module-20-configuration-reference





No comments:

Post a Comment