2017-08-04 2 views
1

私は、create-react-appユーザガイドのdeploymentセクションに指摘されているように、展開用にエクスプレスサーバを使用することを選択しました。高速サーバーはEC2インスタンスにセットアップされ、SSLが終了するAWS Elbの前に位置します。 httpsへのHTTP要求のリダイレクトを設定するにはどうすればよいですか?AWS Elbの背後にあるreactJs SPAのhttpをhttpsにリダイレクトするにはどうすればよいですか?

解決策がある場合は、Nginxも使用できます。

ありがとうございました。ここ

答えて

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

あなたの最良のオプションは、80と443に耳を傾け、あなたのEC2インスタンスにこれらのポートを転送するようにELBを設定することです。 EC2インスタンスでは、Nginxを実行して、localhost上で実行されているエクスプレスサーバにリバースプロキシを適用させることができます。あなたは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

関連する問題