How do I throw a real 404 or 301 with an Angular pushstate URL How do I throw a real 404 or 301 with an Angular pushstate URL angularjs angularjs

How do I throw a real 404 or 301 with an Angular pushstate URL


The real question is does http://example.com/pet/123456 return anything at all?

If your starting point is http://example.com/ and there's a link to http://example.com/pet/123456 then Angular will call the petController which in turn makes an AJAX call to http://example.com/api/pet/123456.

A crawler wouldn't do that but instead would try to call http://example.com/pet/123456 directly.

So your server must be able to handle that call. If there is no pet with the id 123456 then it should return 404. Problem solved. If there is then it should return the SPA. The application should then handle the situation accordingly.


According to this answer How do search engines deal with AngularJS applications?, You should use Headless Browser to process crawlers requests, and serve back snapshots of the page with the appropriate Response Code. https://developers.google.com/webmasters/ajax-crawling/docs/html-snapshot

The google example did not include 301,302 or 404 cases. However, their code could be modified to analyze the content of the snapshot and change the response code.

I found prerender.io offers this service, but it is not free. However, they have a free plan if you have fewer than 250 pages. Prerender asks that in case of 404 or 301, you add a meta tag to the DOM.

<meta name="prerender-status-code" content="404">

this meta tag is then detected by their headless browser and the response code is changed.


Try this

angular.module('pets', [])  .config(function($routeProvider, $locationProvider) {    $locationProvider.html5Mode(true);    $routeProvider.when('/pet/:petId', {      controller: 'petController'    }). otherwise({ yourUrl:'/404.html'}) // Render 404 view;  })