Jignesh zala
2 min readOct 4, 2022

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

});

Original Article published: https://tutscoder.com/post/redirect-301-angular-universal

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Jignesh zala
Jignesh zala

Written by Jignesh zala

MEAN Stack Developer and founder of TutsCoder.com, sharing tech insights, tutorials, and resources on Angular, Node.js, JavaScript, and more for developers.

No responses yet

Write a response