繁体   English   中英

节点服务器中的非www到www重定向无法正常工作

[英]Non www to www redirection in node server not working properly

我必须按照以下代码将非www请求重定向到Node服务器上的www:

app.get('/*', function(req, res, next) {
 if (req.headers.host.match(/^www/) === null ) res.redirect('https://www.' + 
 req.headers.host + req.url, 301);
 else next();
});

但是,如果用户输入foo.com,则不会将其重定向到www.foo.com。 相反,如果foo.com被刷新,那么它将被重定向到www.foo.com。

我也尝试过ForceDomain ,但是问题仍然存在。 我做错什么了吗?

以下是整个代码:

var express=require('express');
var httpsRedirect = require('express-https-redirect');
path=require('path');
bodyParser=require('body-parser');
cors=require('cors');
passport=require('passport');
mongoose=require('mongoose');
config=require('./config/database');
app=express();
app.use('/', httpsRedirect());
port=3700;
app.use(cors());
app.use(bodyParser.json());
app.use(passport.initialize());
app.use(passport.session());
require('./config/passport')(passport);
var users=require('./routes/users');
admin=require('./routes/admin');
app.use('/users',users);
app.use('/admin',admin);
app.use(express.static(path.join(__dirname,'public')));
app.listen(port,function(){console.log('Server logged on '+port)});
mongoose.connect(config.database);
mongoose.connection.on('connected',function(){
});
mongoose.connection.on('error',function(a){
 a&&console.log('Error'+a)
});
// Forcedomain to www

app.get('/*', function(req, res, next) {
  if (req.headers.host.match(/^www/) === null ) res.redirect('https://www.' + req.headers.host + req.url, 301);
  else next();
});

app.get('*',function(a,b){
b.sendFile(path.join(__dirname + '/public/index.html'))
});

我只是发现自己在做什么错。 我已经在使用'express-https-redirect'从http重定向到https,然后尝试将非www重定向到www。 显然,我必须同时做这两项。 因此,我删除了express-https-redirect,并使用ForceDomain重定向到https和www版本。 现在可以了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM