2017-08-04 35 views

回答

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

這裏最好的選擇是配置您的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; 
} 

您還可以找到關於這如我下面鏈接的一些很好的職位。

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

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

+0

感謝您的答覆。但是,我能夠實現一個解決方案,而不必使用nginx。我發佈了下面的解決方案,其中快速服務器本身處理重定向。 – NaveenBabuE

相關問題