如何在meteor.js应用程序中从非www重定向到www
我是《流星》的新手。 它将是冷静的自动重定向从 example.com 到 www.example.com 。如何在meteor.js应用程序中从非www重定向到www,meteor,Meteor,我是《流星》的新手。 它将是冷静的自动重定向从 example.com 到 www.example.com 。 有人能帮忙吗?您可以通过添加一个中间件来实现这一点。这应该让你开始: WebApp.connectHandlers.use(function(req, res, next) { /* Check if request is for non-www address */ if(...) { /* Redirect to the proper addres
有人能帮忙吗?您可以通过添加一个中间件来实现这一点。这应该让你开始:
WebApp.connectHandlers.use(function(req, res, next) {
/* Check if request is for non-www address */
if(...) {
/* Redirect to the proper address */
res.writeHead(301, {
Content-Type': 'text/html; charset=UTF-8',
Location: correctURL,
});
res.end("Moved to: " + correctURL);
return;
}
/* Did not redirect - continue with the application stack */
next();
});
我知道这是2年前的问题,但没有一个公认的答案,所以我提供了一个完整的答案:
WebApp.connectHandlers.use(function(req, res, next) {
// Check if request is for non-www address
if (req.headers && req.headers.host.slice(0, 4) !== 'www.') {
// Add www. from host
var newHost = 'www.' + req.headers.host
// Redirect to www. version URL
res.writeHead(301, {
// Hard-coded protocol because req.protocol not available
Location: 'http://' + newHost + req.originalUrl
});
res.end();
} else {
// Continue with the application stack
next();
}
});
您可以使用以下代码反向(从www到非www):
WebApp.connectHandlers.use(function(req, res, next) {
// Check if request is for non-www address
if (req.headers && req.headers.host.slice(0, 4) === 'www.') {
// Remove www. from host
var newHost = req.headers.host.slice(4);
// Redirect to non-www URL
res.writeHead(301, {
// Hard-coded protocol because req.protocol not available
Location: 'http://' + newHost + req.originalUrl
});
res.end();
} else {
// Continue with the application stack
next();
}
});
我在客户端使用此代码:
Meteor.startup(function () {
if (location.host.indexOf('www.domain.com') !== 0) {
location = 'www.domain.com';
}
});
它非常简单和实用。我希望这能回答你的问题。
谢谢我用nginx=\做的,可能是重复的。参考或这似乎是互联网上唯一的答案。因为我是meteor.js和node.js的新手,所以我很难弄清楚该放在哪里。。。编辑:我用apachevhosts来处理它。它是一个服务器代码,所以你可以把它放在放任何服务器代码的地方。因此,最好在
/server
文件夹中,但也可以在if(Meteor.isServer)
条件中的任何位置。这需要在DNS级别完成。提到