How to redirect 301 in Angular Universal
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 }],
});
}
});