1

I want to send http status code 404, if a route in my angular app is not found. This is not possible by angular directly, because it`s a SPA. How can I tell a seo crawler that a not found route is a 404?

1 Answer 1

1

I found a video, where a guy from Google says, that at least the Google bot handles javascript redirects to 404 correctly: https://www.youtube.com/watch?v=vjj8B4sq0UI&t=30m15s

So I added this routing:

const routes: Routes = [
    ...
    { 
        path: 'not-found-404', 
        component: NotFoundComponent
    },
    { 
        path: '**', 
        component: NotFoundComponent
    },
];

So all not handled routes are redirected to the NotFoundComponent. You can find in-depth infos here

Then I changed my apache server config, to set the status code to 404, if /not-found-404 is loaded

# my .htaccess file (before angular rewrites)
RewriteRule ^not-found-404(\?.*)?$ - [R=404] # Redirect status
ErrorDocument 404 /index.html

Now the server returns a status code 404. And just loads my Angular app as error document.

But this rewrite does not happen when routing inside the app, because there is no page reload when the NotFoundComponent is loaded. So I added this code to ngOnInit of the NotFoundComponent

ngOnInit() {
    this.activatedRoute.queryParams.subscribe(queryParams => {
        if (!queryParams["404_status_code_refresh_done"]) {
            location.href = "/not-found-404?404_status_code_refresh_done=true"
        }
    })
}

It reloads the page with a parameter to avoid an endless loop. This returns a status code 404. Always when I want to trigger a 404 in my app, I can just route to "/not-found-404", and the NotFoundComponent handles the reload with 404 status code.

Does somebody see any disadvantages with this technique? It feels a bit hacky, but it should work, right?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.