使用 express 进行 301 重定向

301 redirects with express

我有一个 node.js 网站,它将取代现有网站。新站点中的某些 URL 与旧站点中的不同,因此我需要为这些设置 301 重定向。

目前我正在使用以下方法重新路由特定页面:

app.get('contact-us', (req, res, next) => { res.redirect(301, 'http://www.example.com/contact'); });

但是有没有办法根据模式重新路由?例如,在旧站点上我有 /products/id/product-name,我需要将其重新路由到 /catalogue/id/product-name

您可以使用 express-redirect 模块以有效的方式完成此操作,

您可以通过发出以下命令来安装它,

npm install express-redirect

要初始化,

var express = require("express")
  , redirect = require("express-redirect");

var app = express();
redirect(app); 

对于重定向,

// just a simple redirect 
app.redirect("/p/:id", "/page/:id");

// you want it permanent? 
app.redirect("/p/:id", "/page/:id", 301);

// if you want to append the query string (?foo=bar) 
app.redirect("/p/:id", "/page/:id", 301, true);

希望对您有所帮助!