After deployment Angular and API on IIS, it's working fine unless I refresh the page. Once refreshed, the web encountered 404 error. In this article, I will explain how to resolve this.
Since Angular is a Single Page Application, which means there is only one single page to render different parts of the page to display content. Therefore, once user goes to a different page and refresh, the new URL is not recognized by Angular and throws the 404 error.
There are 2 ways to resolve this problem if you deploy your application to IIS. They are using HashLocationStrategy and using IIS URL Rewrite. The first strategy works for when you host your API in either same or different location of your Angular project. The second one only works if you host API and Angular separately.
1. HashLocationStrategy
Step 1: Import HashLocationStrategy and LocationStrategy
In app.module.ts
import { HashLocationStrategy, LocationStrategy } from '@angular/common';
Step 2: Include HashLocationStrategy and LocationStrategy in providers
In app.modules.ts
providers: [ {provide : LocationStrategy , useClass: HashLocationStrategy} ]
2. RouterModule.forRoot
Use RouterModule.forRoot with the {userHash:true} argument.
In app-routing.module.ts
import { NgModule } from '@angular/core'; ... const routes: Routes = [//routes in here]; @NgModule({ imports: [ BrowserModule, FormsModule, RouterModule.forRoot(routes, { useHash: true }) ], bootstrap: [AppComponent] }) export class AppModule { }
3. IIS URL Rewrite
Step 1: Download IIS URL Rewrite Extension from Microsoft
Follow below link to download and install the extension:
https://www.iis.net/downloads/microsoft/url-rewrite
Step 2: Create new web.config file and place in IIS folder:
Note: If your application is a subfolder in IIS, the URL in Rewrite part should be the subfolder name.
<?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <rewrite> <rules> <rule name="Angular Routes" stopProcessing="true"> <match url=".*" /> <conditions logicalGrouping="MatchAll"> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> </conditions> <action type="Rewrite" url="/" /> <!-- <action type="Rewrite" url="/yoursubfoldername/" /> --> </rule> </rules> </rewrite> </system.webServer> </configuration>