1

How to force https (redirect http to https) using gulp-connect on Heroku?

I've already configured SSL on Heroku and my website works great if I prefix https:// before the domain.

gulpfile.js

'use strict';

var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var history = require('connect-history-api-fallback');

gulp.paths = {
  src: 'src',
  dist: 'dist',
  tmp: '.tmp',
  e2e: 'e2e'
};

require('require-dir')('./gulp');

gulp.task('default', ['clean'], function () {
  gulp.start('build');
});

gulp.task("serve:production", function(){
  $.connect.server({
    root: './dist',
    port: process.env.PORT || 3004,
    middleware: function(connect, opt) {
      return [
        history({})
      ]
    }
  });
});
4

2 回答 2

2

我以前成功使用过这个包。配置非常简单。

https://www.npmjs.com/package/express-sslify

var express = require('express');
var http = require('http');
var enforce = require('express-sslify');

var app = express();

// Use enforce.HTTPS({ trustProtoHeader: true }) in case you are behind 
// a load balancer (e.g. Heroku). See further comments below 
app.use(enforce.HTTPS());

http.createServer(app).listen(app.get('port'), function() {
    console.log('Express server listening on port ' + app.get('port'));
});
于 2017-04-03T22:25:17.950 回答
0

我已经设法使它与 gulp-connect 一起工作,我在其中创建了express实例,对其进行配置并将其作为中间件传递给连接。

有了这个,我已经在 Heroku 上部署了 SSL 证书,但在我的本地机器上没有配置 SSL。

var connect = require('gulp-connect');
var express = require('express');

gulp.task('connect', function() {

    var app = express();
    app.enable('trust proxy');
    app.use (function (req, res, next) {
            if (req.secure) {
                    next();
            } else {
                if (req.headers.host !== 'localhost:8081'){
                  res.redirect('https://' + req.headers.host + req.url);
                } else {
                    next();
                }
            }
    });

    connect.server({
      port: process.env.PORT || 8081,
      middleware: function(connect, opt) {
        return [app];
      }
    });
});
于 2018-08-19T14:56:58.437 回答