我正在尝试让网站强制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;