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

IT技术 reactjs express nginx http-redirect
2021-05-24 19:33:24

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

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

感谢任何帮助。

3个回答

使用 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 />
    );
  }
}

您最好的选择是将您的 ELB 配置为侦听 80 和 443 并将这些端口转发到您的 EC2 实例。在您的 EC2 实例上,您可以运行 Nginx 并将其反向代理到在本地主机上运行的快速服务器。你需要在你的 Nginx 配置中使用它 -

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name _;
    return 301 https://$host$request_uri;
}

您还可以找到一些关于此的好帖子,例如我在下面链接的帖子。

https://www.nginx.com/resources/admin-guide/reverse-proxy/

https://www.bjornjohansen.no/redirect-to-https-with-nginx

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);