Express.js重定向到HTTPS并发送index.html [英] Express.js redirect to HTTPS and send index.html

查看:234
本文介绍了Express.js重定向到HTTPS并发送index.html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的Express.js实例,为单个页面Angular应用程序提供静态资源。我在Express配置上设置了一些中间件,因此所有路由都会返回index.html,Angular可以从那里加载。

I have a simple Express.js instance that's serving up static assets for a single page Angular app. I set up some middleware on the Express config so that index.html is returned for all routes and Angular can load from there.

最近,我在Heroku上设置了SSL我想确保从HTTP引入的所有流量都被重定向到HTTPS。我试图将来自这篇文章的建议解决方案与我所拥有的现在,但是结束了一个无尽的重定向循环。

More recently, I set up SSL on Heroku and I want to make sure that all traffic that comes in from HTTP is redirected to HTTPS. I tried to combine the suggested solution from this post with what I have now, but end up in an endless redirect loop.

简而言之,我需要将所有流量从HTTP重定向到HTTPS和要发送的index.html文件所有请求我在这里做错了什么?

In short, I need all traffic to be redirected from HTTP to HTTPS and the index.html file to be sent for all requests. What am I doing wrong here?

var gzippo = require('gzippo');
var express = require('express');
var morgan = require('morgan');
var app = express();

// set environment variables
var env = app.get('env') || 'development';

app.use(morgan('dev'));

// serve static assets
app.use(gzippo.staticGzip("" + __dirname + "/dist"));
app.use("/js", express.static(__dirname + "/dist/scripts"));
app.use("/fonts", express.static(__dirname + "/fonts"));
app.use("/img", express.static(__dirname + "/dist/assets/images"));
app.use("/css", express.static(__dirname + "/dist/styles"));


// Redirect all HTTP traffic to HTTPS
function ensureSecure(req, res, next){
  if(req.secure){
    // OK, continue
    return next();
  };
  res.redirect('https://'+req.hostname+req.url); // handle port numbers if you need non defaults
};


// Always send index.html
function sendIndex(req, res, next) {
  res.sendfile('index.html', { root: __dirname + "/dist/"});
}


// Handle environments
if (env == 'production') {
  app.all('*', ensureSecure);
}

app.all('/*', sendIndex);

// Start server
app.listen(process.env.PORT || 5000);


推荐答案

Heroku在负载均衡器级别终止SSL连接,所以 req.secure 永远不会是真的,因为您连接到heroku的负载平衡器不使用SSL,从而创建无限重定向循环。

Heroku terminates SSL connections at the load balancer level, so req.secure will never be true, because your connection to heroku's load balancer is not using SSL, thus creating an infinite redirect loop.

您必须检查 X-Forwarded-Proto 标题:

if(req.headers["x-forwarded-proto"] === "https"){
  // OK, continue
  return next();
};
res.redirect('https://'+req.hostname+req.url);

编辑:您还可以设置 app.enable(trust proxy) 自动快速检查标题。请参阅 http://expressjs.com/guide/behind-proxies.html

you can also set app.enable("trust proxy") to have express check the headers automatically. See http://expressjs.com/guide/behind-proxies.html

这篇关于Express.js重定向到HTTPS并发送index.html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆