404 on refresh or direct navigation

Hello,

My site’s base url is like this (not the real url): example.com
When you navigate to the base url, it automatically goes to example.com/cats/home
But when you copy that link and go directly to example.com/cats/home, the app returns a 404.

I’m running the app on an windows server, and this issue cannot be replicated in my localhost environment.

How can I solve this so that my app is able to be bookmarked by users and so that I can refresh without issue? Thank you.

Hi, you need to add rewrite rules to prevent this 404 problem.

First, make sure the URL Rewrite Module for IIS is installed.

Then, you can add the following rewrite rules to your website’s web.config file:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <!-- ... -->
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="Rewirte rules for Single Page App" 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>

You may be need to adjust some settings for your end to work.

Here is the full web.config of my Ionic Angular site for the reference:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.web>
        <customErrors mode="Off"/>
    </system.web>
    <system.webServer>
        <defaultDocument>
            <files>
                <clear />
                <add value="index.html" />
            </files>
        </defaultDocument>
        <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>

Hope this will help you solve the issue :smile:

Thank you for the response, however my project does not output with a web.config at the moment and I am unsure of how to fix this issue. Manually adding one to the output www folder had no effect.

My project required us to always redirect to the home page on any change to the base URL to prevent manual navigation through the app. So the solution was simple:

Set IIS error page 404 rule to always do a 302 redirect to the home.