Hosting Angular application in IIS Server

We can host an angular application in IIS with the following simple steps.

Build the Angular application

 First build the Angular application using the following command
ng build
Once the build completes successfully it publishes all the build artifacts to the 'dist' folder.

Create a Web application in IIS

Create a Website or Web application and point it to the 'dist' folder in the Angular application.

Install URL Rewrite Module in the IIS

We should install the URL Rewrite Module in IIS, if it not installed already, to handle the deep-linking. We can do it by using Web Platform Installer or manually download and install from https://www.iis.net/downloads/microsoft/url-rewrite

Add web.config file with URL-rewrite rule

Add a web.config file to the root folder of the Angular application (where angular.json file exists) and add the following content
<?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="./index.html" />
      </rule>
     </rules>
   </rewrite>
 </system.webServer>
</configuration>
The above URL rewrite rule will route all the requests, which are not for files or folders, to the root of the application.
As the web.config needs to add in the build, add the following to the angular.json file under "assets" section to copy the web.config file to 'dist' folder when we build the application.
"assets": [
    "app/assets",
    "app/favicon.ico",
    "web.config"
],

Update Base Href value if required

We need to update the base href value in the index.html file based on our hosting type. If we host the application as a website, the base href value should be "/". If we hosted as a web application, the value should be "/<Your web application name>/". 
We can also change this value dynamically while building the application. For that, just use
ng build --base--href "/<Your web application name>/"

Build again

Now build it again to reflect the web.config changes and open the URL in the browser
Happy Coding 😊!!


Gopikrishna

    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment