0
votes

Can't seem to solve this Angular and UI-Router issue. I'm attempting to setup a custom 404 page for my Angular application, but there's an edge case where Angular throws an error rather than handling the route.

My URL is: http://www.example.com/

I have a requirement that the application should have a base path, so I use .NET URL Rewrite to redirect all traffic to the correct location:

http://www.example.com/app/

To make this work, I use the <base> tag in my HTML head section as follows:

<base href="/app/">

Now all my states work with the /app/ prefixed.

$stateProvider
// https://www.example.com/app/
.state('/', {
    url: '/',
    templateUrl: '/Partials/Pages/Home',
  })


  // https://www.example.com/app/login
  .state('login', {
    url: '/login',
    templateUrl: '/Partials/Pages/Login',
  });

To make my 404 page work, I define my last state to intercept any unrecognized path:

// If no state is matched, load the 404 error
$stateProvider.state('404', {
    url: '*path',
    templateUrl: '/Partials/Pages/PageNotFound',
  });

This works almost perfectly. The following URL returns my 404 error: https://www.example.com/app/sdfsf

However, any path that does not begin with my configured base path does not redirect to the 404 error. The following path returns an Angular error: https://www.example.com/login enter image description here

Is there a way to handle 404 errors for any URL that does not begin with my base path?

1

1 Answers

0
votes

First there is a contradiction in this part of your code:

// For any unmatched url, redirect to home
$urlRouterProvider.otherwise('/');

// If no state is matched, load the 404 error
$stateProvider.state('404', {
    url: '*path',
    templateUrl: '/Partials/Pages/PageNotFound',
  });

What you should do is define your '404' state with the others, then otherwise should redirect to it:

$stateProvider
// https://www.example.com/app/
.state('/', {
    url: '/',
    templateUrl: '/Partials/Pages/Home',
  })


.state('404', {
    url: '/404',
    templateUrl: '/Partials/404.html',
  });
$urlRouterProvider.otherwise('/');