In this article, we will learn what is 301 redirect and how it can be implemented in Angular universal.

What is 301 Redirect?

301 is an HTTP status code sent by a web server to a browser.

When a URL is marked with a 301, it means that any users that request the old URL will be instantly redirected to the new URL.

A 301 redirect is most frequently used when a page has been relocated or deleted permanently from a website since it transfers all ranking power from the old URL to the new URL.

How to redirect 301 in Angular Universal

Using 301 redirects in Angular Universal, you can redirect your old page to a new page using the technique described below.

This is by default code in 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 }] });
  });

  The express server(SSR) renders the front-end angular HTML files after all routes arrive here. Therefore, we can transmit the 301 status code before sending the browser any answer.

You can add some conditions like below:

Use Case -1: Redirect HTTP to HTTPS

// All regular routes use the Universal engine
  server.get('*', (req, res) => {
    if (index == req.originalUrl)
      res.redirect(301, 'https://www.tutscoder.com');
    else
      res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
  });

Use Case -2: Convert Underscore to Hyphen

server.get("*", (req, res) => {
    if (req.originalUrl.indexOf("_") > -1) {
      console.log('Before',req.originalUrl);
      req.originalUrl = req.originalUrl.replace(/_/g, "-");
      console.log('After',req.originalUrl);
       res.redirect(
        301,
        req.originalUrl
      );
    }else{
      res.render(indexHtml, {
        req,
        providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }],
      });
    }

  });

Topics covered:

Found this article helpful?

TutsCoder tutorials are free and ad-light — supported by readers like you. Buy me a coffee (or two ☕☕) as a token of appreciation and help keep Angular & Node.js content coming!

One-time. No subscription. 100% optional. 🙏 Every coffee counts!

Leave a Comment

Your email will not be published. Spam-free zone. ✌️

Available for Projects

Need Help With Your
Angular or Node.js Project?

7+ years of MEAN Stack experience. I build scalable Angular 21 apps, Node.js APIs, and SaaS products — delivered on time, every time.

7+ Years MEAN Stack Angular 21 + Nx Expert 20+ Projects Delivered Remote / Freelance