如何将http重定向到AWS Elb后面的reactJs SPA的https? [英] How to redirect http to https for a reactJs SPA behind AWS Elb?

查看:77
本文介绍了如何将http重定向到AWS Elb后面的reactJs SPA的https?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我选择使用Express服务器进行部署,如

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆