0

With Express, how can I redirect all urls with "/something" to the base path "/:=" including additional paths to their respective pages. For example, I want to redirect the following:

  1. "/something" to "/"
  2. "/something/else" to "/else"
  3. "/something/else/again" to "/else/again"
  4. etc...

How can I achieve that with Express?

var express = require('express');
var router = express.Router();

router.get('/something/*', function(req, res) {
  res.redirect('/');
});

module.exports = router;
cusejuice
  • 10,285
  • 26
  • 90
  • 145

1 Answers1

4

req.originalUrl will give you original path and from that you need to remove the something part. Can you try:

router.get('/something/*', function(req, res) {
  var newPath = req.originalUrl.split('something')[1]
  res.redirect(newPath);
});

You can also use req.path, but there are some scenarios it might not work.

Community
  • 1
  • 1
Arun Ghosh
  • 7,634
  • 1
  • 26
  • 38