Azure hosted website gives 404 error when domain name is preceded by www

azuredomain-namedomain-name-system

mydomain.com works fine.
www.mydomain.com gives 404 - File or directory not found.

I don't want people to use www.mydomain.com instead of mydomain.com, but I also don't want the 404 error in their face if the do.

The A record at GoDaddy looks like:
Host – Points to – TTL
@ – ip address – 600 seconds

How to fix the issue so that if user types in www.mydomain.com they would be magically redirected to mydomain.com?

Best Answer

The solution to the problem was to have both domain names (mysite.com and www.mysite.com) explicitly set up in Azure as custom domains.

Then to use URL rewrite module in IIS (already installed in Azure) by adding rewrite section in the Web.config file:

<system.webServer>
<rewrite>
  <rules>
    <clear />
    <rule name="WWW Rewrite" stopProcessing="true" enabled="true">
      <match url=".*" />
      <conditions>
        <add input="{HTTP_HOST}" pattern="^www[.](.+)" />
      </conditions>
      <action type="Redirect" url="http://{C:1}/{R:0}" redirectType="Permanent" />
    </rule>
  </rules>
</rewrite>
</system.webServer>
Related Topic