skip to Main Content

Let’s say my app is running on domain.com and most of links in the internet to this site looks like this: domain.com/:id.

I want to improve SEO a little bit and add redirects (301):
domain.com/:id => domain.com/:title. But to get title for id I have to run angular app and check this in DB.

So what I want to do is:

  1. User go to domain.com/:id
  2. Check title for id from url inside angular app
  3. Redirect user with 301 status to domain.com/:title

2

Answers


  1. You have to run Angular using Angular Universal with server-side rendering. There is a guide to get you started, and if it’s a new Angular project it’s relatively easy to add.

    https://angular.io/guide/universal

    You then have to tell Express to perform a 301 redirect, and this can be done by configuring the main module used for SSR.

    https://gist.github.com/KostyaEsmukov/ce8a6486b2ea596c138770ae393b196f

    Login or Signup to reply.
  2. You can make some changes or by adding a condition in your server.ts file.

    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 get more detail on this article

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search