[英]How to redirect from non www to www in meteor.js app
我是流星的新手。 自動重定向會很酷
example.com
至
www.example.com
。 有人可以幫忙嗎?
我知道這是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();
}
});
您可以通過添加一個中間件來完成此操作。 這應該讓你開始:
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();
});
我在客戶端使用此代碼:
Meteor.startup(function () {
if (location.host.indexOf('www.domain.com') !== 0) {
location = 'www.domain.com';
}
});
它的簡單和工作。 我希望這能回答你的問題。 謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.