我选择使用express server进行部署,如create-react-app用户指南的deployment部分所述。 Express服务器在EC2实例上设置,并由AWS Elb提供,SSL终止。如何设置http请求重定向到https?
如果有解决方案,我也愿意使用Nginx。
感谢任何帮助。
答案 0 :(得分:2)
format
假设一个CommonJS环境,您只需以这种方式使用该组件:
npm install --save react-https-redirect
答案 1 :(得分:0)
这里最好的选择是将ELB配置为侦听80和443并将这些端口转发到EC2实例。在EC2实例上,您可以运行Nginx并将其反向代理到在localhost上运行的快速服务器。您在Nginx配置中需要这个 -
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
return 301 https://$host$request_uri;
}
您还可以找到一些关于此的好帖子,例如我在下面链接的帖子。
答案 2 :(得分:0)
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);