如何将http重定向到AWS Elb后面的reactJs SPA的https?

编程入门 行业动态 更新时间:2024-10-27 10:26:42
本文介绍了如何将http重定向到AWS Elb后面的reactJs SPA的https?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我选择使用Express服务器进行部署,如部署部分.快速服务器在EC2实例上设置,并在AWS Elb的前面,SSL终止于此.如何设置将HTTP请求重定向到https?

I chose to use express server for deployment as pointed to in deployment section of create-react-app user guide. The express server is set up on an EC2 instance and is fronted by an AWS Elb, where the SSL terminates. How do I setup redirection of http requests to https?

如果有解决方案,我也愿意使用Nginx.

I am open to using Nginx as well, if there is a solution.

感谢任何帮助.

推荐答案

const express = require('express'); const path = require('path'); const util = require('util'); const app = express(); /** * Listener port for the application. * * @type {number} */ const port = 8080; /** * Identifies requests from clients that use http(unsecure) and * redirects them to the corresponding https(secure) end point. * * Identification of protocol is based on the value of non * standard http header 'X-Forwarded-Proto', which is set by * the proxy(in our case AWS ELB). * - when the header is undefined, it is a request sent by * the ELB health check. * - when the header is 'http' the request needs to be redirected * - when the header is 'https' the request is served. * * @param req the request object * @param res the response object * @param next the next middleware in chain */ const redirectionFilter = function (req, res, next) { const theDate = new Date(); const receivedUrl = `${req.protocol}:\/\/${req.hostname}:${port}${req.url}`; if (req.get('X-Forwarded-Proto') === 'http') { const redirectTo = `https:\/\/${req.hostname}${req.url}`; console.log(`${theDate} Redirecting ${receivedUrl} --> ${redirectTo}`); res.redirect(301, redirectTo); } else { next(); } }; /** * Apply redirection filter to all requests */ app.get('/*', redirectionFilter); /** * Serve the static assets from 'build' directory */ app.use(express.static(path.join(__dirname, 'build'))); /** * When the static content for a request is not found, * serve 'index.html'. This case arises for Single Page * Applications. */ app.get('/*', function(req, res) { res.sendFile(path.join(__dirname, 'build', 'index.html')); }); console.log(`Server listening on ${port}...`); app.listen(port);

更多推荐

如何将http重定向到AWS Elb后面的reactJs SPA的https?

本文发布于:2023-11-01 19:46:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1550236.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何将   重定向   http   AWS   https

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!