本文介绍了如何将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?
发布评论