Apex domain redirect for Azure Static Web Apps
After reimplementing redirects in Azure Static Web App using managed Azure Functions, there was one last redirect I couldn't implement in this way and had to find another solution for: redirecting all apex domain requests to their counterparts with www subdomain.
In IIS, I used URL rewrite module to implement it:
<rule name="Redirect to www">
<match url=".*" />
<conditions logicalGrouping="MatchAny">
<add input="{HTTP_HOST}" pattern="^(www\.)(.*)$" negate="true" />
</conditions>
<action type="Redirect" url="https://www.{HTTP_HOST}/{R:0}" redirectType="Permanent"/>
</rule>
For Azure Static Web App, I ended up doing it as part of my custom domain setup. First, I had set up both custom domains: www and apex.
The simper of the two was the www subdomain:
- In my DNS configuration I had to add a
CNAMEentry pointing at the autogeneratedazurestaticapps.netURL of my Azure Static Web App listed on its Overview page in Azure Portal. - On the Custom domains page of the Azure Static Web App in Azure Portal, I had to add an entry for my
wwwdomain withCNAMEtype. After it was validated, the web page started responding at mywwwsubdomain.
Setting up the apex domain was a bit more involved. Since my domain registrar doesn't support ALIAS records or domain forwarding, I had to go the A record route:
- To validate the domain, I had to add an entry on the Custom domains page for my apex domain with type
TXT. This generated a code for me which I had to enter as the value for the correspondingTXTentry in my DNS configuration. - Once the
TXTentry was validated, it was time to add anAentry for the apex domain in my DNS configuration. I got the value for it, i.e., the IP, in thestableInboundIPfield of the JSON view on the Overview page of my Azure Static Web App in Azure Portal.
After all of this was successfully set up, it was time for the very last step: configuring the redirect from the apex domain to the www subdomain. I could achieve this by setting my www subdomain entry on the Custom domains page in Azure Portal as default. As a side effect, this also redirects any requests from the autogenerated azurestaticapps.net domain to my www custom subdomain. I don't expect (m)any such requests, but it's still nice to have this redirect in place.
