Search code examples
angularazurehttp-redirectweb-applicationsstatic

azure static webapp redirect subdomain to internal path


I am running an angular app with Azure static web app. Is there a way to redirect subdomain to an internal path.

Let's say : abc.mydomain.com. to mydomain.com/abc

I have already configured CNAME in my DNS. I have tried configuring a .htaccess file. ( and web.config. even I know server is ubuntu). None of them working. Tried also configuring staticwebapp.config.json but it seems to be working for internal route not subdomain.

Thanks in advance


Solution

  • You can add the redirect route in your code directly and edit your staticwebapp.config.json like below:-

    app-routing.module.ts

    import { NgModule } from '@angular/core';
    import { Routes, RouterModule } from '@angular/router';
    import { HomeComponent } from './home/home.component'; 
    const routes: Routes = [
      { path: '', component: HomeComponent },
      { path: 'abc', component: AbcComponent },
    
    @NgModule({
      imports: [RouterModule.forRoot(routes)],
      exports: [RouterModule]
    })
    export class AppRoutingModule { }
    

    staticwebapp.config.json

    {
      "routes": [
        {
          "route": "/abc/*",
          "rewrite": "/index.html"
        }
      ]
    }
    

    If you do not have route add the code directly to your app.component.ts:-

    import { Component } from '@angular/core';
    import { ActivatedRoute, Router } from '@angular/router';
    
    @Component({
      selector: 'app-root',
      template: `
        <div>
          <router-outlet></router-outlet>
        </div>
      `,
    })
    export class AppComponent {
      constructor(private route: ActivatedRoute, private router: Router) {
        this.route.url.subscribe(url => {
          const path = url[0].path;
          if (path === 'abc') {
            window.location.href = 'https://customdomain.com/abc';
          }
        });
      }
    }
    

    enter image description here