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;

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...