在heroku上使用https

时间:2014-07-13 20:26:38

标签: ssl heroku

我试图让我的应用程序在heroku上随处可见' https'。到目前为止应用程序是这样的:

"use strict";

console.log('working');

//Initial setup
var path, https, privateKey, certificate, port, cdjshelp, util, cookies, oauth, twitter, crypto, _, options, express, auth, lodash, dust, dustjs,
    dustjsHelpers, commonDustjsHelpers, app, db, fs, mongoose, mongooseTimes, Comment, Bird, Sighting, Site, User,
    Backbone, io;

//node modules, express and dust declarations
path = require('path');
util = require('util');
fs = require('fs');
https = require('https');
privateKey = fs.readFileSync('./config/privatekey.pem').toString();
certificate = fs.readFileSync('./config/certificate.pem').toString();
crypto = require('crypto');

//APP Defn...
app = require('./config/appSetup')(dustjs);

//******** SERVER CONFIG **********//
var port = process.env['PORT'] = process.env.PORT || 4000; // Used by https on localhost

options = {
    key: privateKey,
    cert: certificate
}

https.createServer(options, app).listen(port, function() {
    console.log("Express server listening with https on port %d in %s mode", this.address().port, app.settings.env);
});

我已经使用openSSL CLI生成了privatekey.pem和certificate.pem并将它们作为选项加载。

我知道如果您使用DNS记录将应用程序提供给您自己的域,则heroku会有一个程序。我知道您必须完成列出的here程序。我没有重新映射任何网址或更改任何记录 - 我的网址是birdsapp.heroku.com。

Heroku使用搭载SSL,因此如果您设置了http服务器,您的应用将响应https请求而无需任何其他配置。问题是http路由仍然可用,所以我一直坚持设置https服务器 - 但是它在日志中没有任何时间,所以我认为存在问题使用SSL设置。

以上设置是否正确?这是在heroku上执行基本https服务器的最佳方式吗?

1 个答案:

答案 0 :(得分:1)

好吧,它实际上比那简单得多......

您只需创建一个http服务器:

//******** SERVER CONFIG **********//
var port = process.env['PORT'] = process.env.PORT || 4000;

http.createServer(app).listen(port, function() {
    console.log("Express server listening with http on port %d in %s mode", this.address().port, app.settings.env);
});

并添加路线重定向:

app.all('*', function(req, res, next) {
    if (req.headers['x-forwarded-proto'] != 'https')
        res.redirect('https://' + req.headers.host + req.url)
    else
        next() /* Continue to other routes if we're not redirecting */
});

heroku负责其余部分,设置一个http服务器,它是您的http服务器的镜像并使用他们的证书等。

相关问题