微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 在Elastic Beanstalk上使用Node / Express重定向到HTTPS

我正在尝试让网站强制HTTPS(从HTTP重定向).我们已经通过AWS Elastic Beanstalk设置了HTTPS.问题是,目前,可以使用HTTP和HTTPS.

在阅读了包括this one在内的几篇文章之后,下面的代码就是我想出的.不幸的是,这不起作用.

我错过了什么?

import express from 'express';
import { join } from 'path';

const app = express();
const buildpath = join(`${__dirname}/../build`);
const enforceHTTPS = (req,res,next) => {
  if (req.headers['x-forwarded-proto'] === 'https') return next();
  else return res.redirect(301,join(`https://${req.hostname}${req.url}`));
};

app.use(express.static(buildpath));
app.use(enforceHTTPS);
app.get('*',(req,res) => res.sendFile(`${buildpath}/index.html`));
app.listen(process.env.PORT || 3000,() => console.log('Server running on port 3000!'));

export default app;

解决方法

事实证明,我只需要重新排序我的app.use语句 – 在提供静态文件之前调用重定向.

此外,为了使其能够在IE / Edge上运行,需要将“https://”移动到path.join之外(join删除第二个正斜杠,尽管所有其他主流浏览器都能正确处理它,IE不会’喜欢它).

这是一个有效的例子:

import express from 'express';
import { join } from 'path';

const app = express();
const buildpath = join(`${__dirname}/../build`);
const enforceHTTPS = (req,next) => {
  if (req.headers['x-forwarded-proto'] === 'https') return next();
  return res.redirect(301,`https://${join(req.hostname,req.url)}`);
};

app.use(enforceHTTPS);
app.use(express.static(buildpath));
app.get('*',() => console.log('Server running on port 3000!'));

export default app;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐