I recently migrated my blog to a brand new Angular App that is hosted using Firebase Hosting. I needed my old blog posts that were at /posts/blog-post-name to redirect to /blog/blog-post-name.
I needed to have the redirects be server side 301 redirects in order to preserve any SEO link juice from my the previous blog posts.
How to Handle Redirects
Handling redirects in an Angular App comes down to two options:
- Client Side Redirects: If you simply want to have your users redirected to the correct content, use this option. This won’t transfer your SEO link juice if you previously had links pointing to your source URL.
- Server Side Redirects: If you are worried about transferring the previous route’s SEO link juice, I recommend Server Side Redirects.
Client Side Redirects
Client Side Redirects are the easiest option if you want your users to be directed to the correct content, your server will send a 200 and then redirect within your Angular App.
Simply add a redirect route to the Routes object in your app-routing.module.ts file in your Angular project. The path value is your source or “original route”, and the redirectTo value is the route that you want your user to be redirected to.
Here is an example app-routing.module.ts:
With the routing listed above, when I try to navigate to:
I will be redirected to:
Server Side Redirects
Server Side Redirects are the best option for preserving SEO link juice because when a bot crawls your old route/link it will be instantly notified with a 301 Redirect to navigate to the new route/link. This is useful because the crawler will know that your link has moved permanently.
Setting up Server Side Redirects in Firebase Hosting is actually quite easy, all you need to do is edit the firebase.json file at the root of your Angular project.
Simply add a redirects section to your firebase.json file, the source value is the original route/link and the destination value is the route/link that you want your user to be redirected to.
The type value in your redirects section should be 301 (Moved Permanently), but you can also set it to 302 (Moved Temporarily). If you are not sure which redirect value to use, read more here: 301 redirect vs 302 redirect.
Here is an example firebase.json that handles Server Side Redirects:
I hope this helped you to better understand how to properly handle redirects in both your Angular App and in Firebase hosting.
I also hope you learned about the differences between client-side and server-side redirects.