DEV Community

loading...
Cover image for How to redirect 301 HTTP in angular

How to redirect 301 HTTP in angular

eavnitech profile image eavnitech Originally published at eavnitech.com Updated on ・2 min read

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 not 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 redirect in angular?

As we know angular is a front end framework to build a Single page application but 301 redirects can be integrated with angular universal server-side rendering(SSR).

implementation

You can make some changes or by adding a condition in your server.ts file
in the server.ts file

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

  });

Enter fullscreen mode Exit fullscreen mode

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 }] });
    }
  });

Enter fullscreen mode Exit fullscreen mode

You can update your server.ts file as like then run npm run build and npm start and test it.

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

Discussion (0)

pic
Editor guide