2017-02-28 6 views
0

私はAWSのWindowsとNode.js上で動作するアプリケーションを持っています。私はhttpとhttpsを使ってアクセスできます。しかし、誰かがhttpを使ってアクセスする場合、httpをhttpsに転送する必要があります。 私はいろいろ考えることができますが、最良のアプローチについてのアドバイスを感謝します。サーバーはEC2インスタンスであり、ロードバランサを通じてアクセスされます。フォワードHTTPからHTTPS - AWS Windows Node.js

答えて

1

あなたは急行を使用している場合は、このミドルウェアモジュールは、HTTPSを強制することが容易になります:https://www.npmjs.com/package/express-force-ssl

アプリ(ELB、nginxの、など)の前でリバースプロキシを使用している場合は、あなた'LL信頼プロキシ設定を設定する必要があります。

ここで上記モジュールなしのサンプルです:

// Forward all requests to HTTPS. 
    // enable reverse proxy support in Express. This causes the 
    // the "X-Forwarded-Proto" header field to be trusted so its 
    // value can be used to determine the protocol. See 
    // http://expressjs.com/api#app-settings for more details. 
    app.enable('trust proxy'); 

    // Add a handler to inspect the req.secure flag (see 
    // http://expressjs.com/api#req.secure). This allows us 
    // to know whether the request was via http or https. 
    app.use((req, res, next) => { 
     if (req.secure) { 
     // request was via https, so do no special handling 
     next(); 
     } else { 
     // request was via http, so redirect to https 
     console.log('Redirecting to https'); 
     res.redirect('https://' + req.headers.host + req.url); 
     } 
    }); 

完全なサンプルは、非GETは

app.all('*', (req, res, next) => { 
    if (req.secure) { 
     next(); 
    } else if (req.method === 'GET') { 
     res.redirect(`https://${req.headers.host}${req.url}`); 
    } else { 
     res.status(401).send('Secure channel required'); 
    } 
    }); 
+0

を要求したため、エラーで応答し、

var express = require('express'); var app = express(); // Forward all requests to HTTPS. // enable reverse proxy support in Express. This causes the // the "X-Forwarded-Proto" header field to be trusted so its // value can be used to determine the protocol. See // http://expressjs.com/api#app-settings for more details. app.enable('trust proxy'); // Add a handler to inspect the req.secure flag (see // http://expressjs.com/api#req.secure). This allows us // to know whether the request was via http or https. app.use((req, res, next) => { if (req.secure) { // request was via https, so do no special handling next(); } else { // request was via http, so redirect to https console.log('Redirecting to https'); res.redirect('https://' + req.headers.host + req.url); } }); // Respond to any GET requests with our message app.get('*', (req, res) => { res.send('This is only served over https'); }); // Listen on the assigned port var port = process.env.PORT || 3001; app.listen(port); console.log('Hello started on port ' + port); 

RedirectがGETリクエストapp.jsありがとう、これは私が何をしているかと非常に近いです。現在、「送信後にヘッダーを設定できません」というメッセージが表示されます。コードをさらに上げようとしていましたが、「未定義のプロパティを有効にできません」というメッセージが表示されます。申し訳ありませんが、私は非常にノードに新しい:-) –

+0

私は上記の答えに完全なサンプルアプリケーションを追加しました。それをapp.jsとして保存してから '' node app.js''を実行してください。 – bsyk

+1

それはマジックラインで働いていました。リダイレクトの前に "return"を追加しなければなりません。ありがとうございます。 –

関連する問題