我選擇使用快速服務器進行部署,如在create-react-app用戶指南的deployment部分中指出的那樣。快速服務器在EC2實例上設置,並由SSL終止的AWS Elb前端。如何設置http請求重定向到https?如何將http重定向到https後面的AWS Elb後面的reactJs SPA?
我也願意使用Nginx,如果有解決方案。
感謝任何幫助。
我選擇使用快速服務器進行部署,如在create-react-app用戶指南的deployment部分中指出的那樣。快速服務器在EC2實例上設置,並由SSL終止的AWS Elb前端。如何設置http請求重定向到https?如何將http重定向到https後面的AWS Elb後面的reactJs SPA?
我也願意使用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);
這裏最好的選擇是配置您的ELB在80和443上偵聽並將這些端口轉發到您的EC2實例。在您的EC2實例上,您可以運行Nginx,並將其反向代理到運行在本地主機上的express服務器。你需要這在Nginx的配置 -
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
return 301 https://$host$request_uri;
}
您還可以找到關於這如我下面鏈接的一些很好的職位。
感謝您的答覆。但是,我能夠實現一個解決方案,而不必使用nginx。我發佈了下面的解決方案,其中快速服務器本身處理重定向。 – NaveenBabuE