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

Nav*_*buE 5 nginx http-redirect express reactjs

我选择使用 express 服务器进行部署,如create-react-app 用户指南的部署部分所述。快速服务器设置在 EC2 实例上,并以 AWS Elb 为前端,SSL 在此终止。如何设置将 http 请求重定向到 https?

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

感谢任何帮助。

小智 5

使用 npm:

npm install --save react-https-redirect

假设有一个 CommonJS 环境,你可以简单地这样使用组件:

import HttpsRedirect from 'react-https-redirect';
class App extends React.Component {

  render() {
    return (
          <Providers>
            <HttpsRedirect>
              <Children />
            </HttpsRedirect>
           <Providers />
    );
  }
}
Run Code Online (Sandbox Code Playgroud)


Nav*_*buE 2

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);
Run Code Online (Sandbox Code Playgroud)