Slee
Slee

Reputation: 28278

azure website rewrite rule in web.config to redirect .net to .com

I want to make sure all .net traffic goes to my .com so I created this rule but I am sure I am doing this wrong since it is not working:

 <rule name=".net to .com" enabled="true" stopProcessing="true">
        <match url=".*mywebsite.net.*"/>
        <action type="Redirect" url="https://mywebsite.com/" appendQueryString="false" redirectType="Permanent"  />
      </rule>

I assumed I had this regex written properly, but regex is not my strong point

Upvotes: 1

Views: 1063

Answers (1)

David Faber
David Faber

Reputation: 12495

There is an issue with your regex BUT this is not generally how canonical domain name rules (which is what you want in this case) are set up. Generally you want to match every URL that comes in to your server and then filter the values of CGI environment variables (in this case, HTTP_HOST). Your rewrite rule would look something like this:

<rule name="CanonicalHostNameRule1" stopProcessing="true">
    <match url="(.*)" />
    <conditions>
        <add input="{HTTP_HOST}" pattern="^mywebsite\.com$" negate="true" />
    </conditions>
    <action type="Redirect" url="https://mywebsite.com/{R:1}" appendQueryString="false" redirectType="Permanent" />
</rule>

What this will do is forward all requests from URLs that aren't http://mywebsite.com or https://mywebsite.com to https://mywebsite.com. The actual URL is captured in the match and put in the parameter {R:1} - this way, if you go to say http://www.mywebsite.net/home.php, it will be redirected to https://mywebsite.com/home.php.

Also, if you want to enforce HTTPS, you can do the following:

<rule name="CanonicalHostNameRule1" stopProcessing="true">
    <match url="(.*)" />
    <conditions logicalGrouping="MatchAny">
        <add input="{HTTPS}" pattern="^on$" negate="true" />
        <add input="{HTTP_HOST}" pattern="^mywebsite\.com$" negate="true" />
    </conditions>
    <action type="Redirect" url="https://mywebsite.com/{R:1}" appendQueryString="false" redirectType="Permanent" />
</rule>

The first condition will check if cgi.HTTPS is "on" ... and if it isn't, redirect to an HTTPS URL.

Note: If you want to redirect only mywebsite.net URLs, then the condition might look like this:

<add input="{HTTP_HOST}" pattern="mywebsite\.net$" />

Hope this helps.

Upvotes: 1

Related Questions