使用Node.js和Express将非www重定向到www [英] Redirect non-www to www with Node.js and Express
本文介绍了使用Node.js和Express将非www重定向到www的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在提供一个静态目录,如下所示:
I am serving a static directory like so:
var app = express.createServer();
app.configure(function(){
app.use(express.static(__dirname + '/public'));
});
所以我根本没有使用路由.我想将example.com重定向到www.example.com,可以使用Express吗?
So I am not using routes at all. I would like to redirect example.com to www.example.com, is this possible using Express?
推荐答案
是.这应该做.
var express = require("express");
var app = express.createServer();
var port = 9090;
app.all(/.*/, function(req, res, next) {
var host = req.header("host");
if (host.match(/^www\..*/i)) {
next();
} else {
res.redirect(301, "http://www." + host);
}
});
app.use(express.static(__dirname + "/public"));
app.listen(port);
这篇关于使用Node.js和Express将非www重定向到www的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文