[英]Redirect non-www to www with Node.js and Express
I am serving a static directory like so: 我正在服务一个静态目录,如下所示:
var app = express.createServer();
app.configure(function(){
app.use(express.static(__dirname + '/public'));
});
So I am not using routes at all. 所以我根本不使用路线。 I would like to redirect example.com to www.example.com, is this possible using Express?
我想将example.com重定向到www.example.com,这是否可以使用Express?
The following code preserve path while redirecting 以下代码在重定向时保留路径
Ex: http://foo.com/foo to http://www.foo.com/foo 例如: http : //foo.com/foo到http://www.foo.com/foo
var app = express.createServer();
self.app.all(/.*/, function(req, res, next) {
var host = req.header("host");
if (host.match(/^www\..*/i)) {
next();
} else {
res.redirect(301, "http://www." + host + req.url);
}
});
app.use('/',express.static('public'));
Yes. 是。 This should do it.
这应该做到这一点。
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);
Alternatively, you can use a ready-made module for Express that does exactly what you want, eg node-force-domain. 或者,您可以使用现成的Express模块来完成您想要的操作,例如node-force-domain。
See https://github.com/goloroden/node-force-domain for details. 有关详细信息,请参阅https://github.com/goloroden/node-force-domain 。
You can use express-force-domain package from npm: 你可以使用npm的express-force-domain包:
//install
npm install express-force-domain
///app.js
app.all('*', require('./express-force-domain')('http://www.example.com') );
Package on npm: https://npmjs.org/package/express-force-domain 在npm上打包: https ://npmjs.org/package/express-force-domain
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.