angulariisweb-config

Web.Config rewrite rule for Angular application to handle invalid files/directories


I have a web.config rewrite rule setup for angular application as below

 <rule name="Angular" stopProcessing="true">
                    <match url="^(?!^bff).*" />
                    <conditions logicalGrouping="MatchAll">
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="/" />
                </rule>

Problem: The issue is that Angular allows requests for non-existent files to return a 200 OK status, causing the application to hang at the current route since the request cannot be served.

for ex: http://domain/svg/fileexist.svg - file exists and return with status 200

http://domain/svg/filenotexisit.svg - file does not exist but passed with status 200 and app hangs

Expected Result: The Angular application should continue to allow requests for files and directories, but should return a 404 status if an invalid file or directory is requested.

for ex: http://domain/svg/fileexist.svg - file exists and return with status 200

http://domain/svg/filenotexisit.svg - file does not exist and should return status 404

Observation: This behavior works correctly in a basic Angular 17 app running locally. However, when the Angular app is hosted on IIS with the specified web.config rewrite rule, IIS does not handle invalid file requests properly.

Request for Assistance: Any suggestions on how to address this scenario would be greatly appreciated.


Solution

  • Thanks everyone for your contribution.

    I have solved this problem by adding another rule just above the existing rule

    <match url="\.\w{2,4}($)" />
    <conditions logicalGrouping="MatchAll">
    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
    </conditions>
    <action type="CustomResponse" statusCode="404" />
    </rule>