2017-08-04 90 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