【问题标题】:Redirect all requests in ExpressJS except the main index page?重定向 ExpressJS 中除主索引页面之外的所有请求?
【发布时间】:2013-07-26 23:19:36
【问题描述】:

我在 Heroku 上托管一个 ExpressJS/AngularJS 站点,并且我正在使用 Express 将所有非 https 请求重定向到 https 版本。

我的问题是 - 我不想重定向主页 - 其他一切,是的。我只想在没有 https 重定向的情况下提供主页。任何想法如何用 Express 做到这一点?

非常感谢!

app.get('*',function(req,res,next){
    if( req.headers['x-forwarded-proto'] != 'https' )
        res.redirect('https://mydomain.com'+req.url)
    else
        next() /* Continue to other routes if we're not redirecting */
})

app.use(express.static(__dirname));
app.listen(port);

【问题讨论】:

    标签: angularjs express


    【解决方案1】:
    app.all('*', function(req, res, next){
      if(req.path === '/'){
        next();
      } else if(req.secure){
        next();
      } else {
        var port = 443;  // or load from config
        if(port != 443){
          res.redirect('https://'+req.host+':'+port+req.originalUrl);
          console.log('redirecting to https://'+req.host+':'+port+req.originalUrl);
        } else {
          res.redirect('https://'+req.host+req.originalUrl);
          console.log('redirecting to https://'+req.host+req.originalUrl);
        };
      };
    });
    

    【讨论】:

    • 哇!棒呆了的家伙。让我想想这个。非常好。
    • 把它放在所有其他路由之上,因为 express 会按照您调用 app.get() 等的顺序优先考虑路由
    • 哦,哎呀,我刚刚意识到我做了app.get(),我正在将其编辑为app.all(),因此它适用于例如发布
    【解决方案2】:
    if (process.env.DEVMODE == 'dev'){
        if( req.headers['x-forwarded-proto'] != 'https' )
            if !(req.url == homeURL)
               res.redirect('https://mydomain.com'+req.url)
        else
            next() /* Continue to other routes if we're not redirecting */
      } else {
            next();
      }
    })
    

    【讨论】:

    • 谢谢蒙肖先生。您将如何定义 homeURL?这就是我遇到麻烦的部分。干杯
    • 你的意思是你的 home url,heroku home url,还是一般的 home url?
    • 我认为柏拉图的“if req.path === '/'”回答了我的问题。我使用的是 req.url 而不是 req.path。谢谢!
    猜你喜欢
    • 2016-11-30
    • 1970-01-01
    • 1970-01-01
    • 2020-03-11
    • 2016-10-17
    • 1970-01-01
    • 2020-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多