How to redirect 301 HTTP in angular

Hello guys, today we will discuss the 301 HTTP redirect in angular.

What is 301 redirect?

So 301 is an HTTP status code, that is sent by the server to the browser so the browser will know that the requested URL is now moved to new location lets take an example a browser sends a request www.example.com/request-1, now the server will review it and if the URL moved on new location then will send the 301 HTTP status with a new location

Now the browser will know the old location is moved and will send a new request to the received location.

Why need it

We need it for the SEO, as the search engine bots crawl the site URLs daily if any URL does not exist then the BOT will mark that URL as 404 and it is not good for SEO. so we tell the bots with 301 status that the old user is now moved on the new location, please crawl the new URL.

How can we add HTTP 301 in angular?

As we know angular is a front end javascript framework, it is used to build a Single page application so the question is how 301 redirection can be added on some URLs becuase angular renders on the client side(browser) and HTTP 301 status is send by the server. So 301 HTTP redirect can be integrated in angular with angular universal server-side rendering(SSR).

implementation of HTTP 301 in angular

Once you install the angular setup then on the root folder, there should be a file server.ts. You can make some changes or can add conditions in your server.ts file like this.

This is by default code in server.ts file


// This code should be in your server.ts file
// All angular routes use the Universal engine
  server.get('*', (req, res) => {
	 res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
	
  });
  

in the listed code, all routes first come here then the express server(SSR) render the front end angular HTML files. so before sending any response to the browser we can send the 301 status code. we can add the condition like this


  // All regular routes use the Universal engine
  server.get('*', (req, res) => { 
   // req.originalUrl in this object we can read the requested URL
	if(req.originalUrl == '/old-url-example'){		
		res.redirect(301, 'http://localhost:4000/new-url');
	}else{
		res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
	}
  });
  
  
  • You can update your server.ts file as like
  • Run npm run build to build the App
  • Runnpm start to run the server and test it.

I will be happy to answer your queries on my Twitter handle Twitter


Related blog of angular


Designed with BootstrapMade & Built with Next.Js