Heroku NodeJS http 到 https ssl 强制重定向

我有一个应用程序在 Heroku 上运行,在 Node.js 上运行 Express.js,在 https上运行。如何识别在 Heroku 上使用 Node.js 强制重定向到 https的协议?

我的应用程序只是一个简单的 http服务器,它(还)没有意识到 Heroku 正在向它发送 https请求:

// Heroku provides the port they want you on in this environment variable (hint: it's not 80)
app.listen(process.env.PORT || 3000);
58462 次浏览

The answer is to use the header of 'x-forwarded-proto' that Heroku passes forward as it does it's proxy thingamabob. (side note: They pass several other x- variables too that may be handy, check them out).

My code:

/* At the top, with other redirect methods before other routes */
app.get('*',function(req,res,next){
if(req.headers['x-forwarded-proto']!='https')
res.redirect('https://mypreferreddomain.com'+req.url)
else
next() /* Continue to other routes if we're not redirecting */
})

Thanks Brandon, was just waiting for that 6 hour delay thing that wouldn't let me answer my own question.

Checking the protocol in the X-Forwarded-Proto header works fine on Heroku, just like Derek has pointed out. For what it's worth, here is a gist of the Express middleware that I use and its corresponding test.

I've written a small node module that enforces SSL on express projects. It works both in standard situations and in case of reverse proxies (Heroku, nodejitsu, etc.)

https://github.com/florianheinemann/express-sslify

As of today, 10th October 2014, using Heroku Cedar stack, and ExpressJS ~3.4.4, here is a working set of code.

The main thing to remember here is that we ARE deploying to Heroku. SSL termination happens at the load balancer, before encrypted traffic reaches your node app. It is possible to test whether https was used to make the request with req.headers['x-forwarded-proto'] === 'https'.

We don't need to concern ourselves with having local SSL certificates inside the app etc as you might if hosting in other environments. However, you should get a SSL Add-On applied via Heroku Add-ons first if using your own certificate, sub-domains etc.

Then just add the following to do the redirect from anything other than HTTPS to HTTPS. This is very close to the accepted answer above, but:

  1. Ensures you use "app.use" (for all actions, not just get)
  2. Explicitly externalises the forceSsl logic into a declared function
  3. Does not use '*' with "app.use" - this actually failed when I tested it.
  4. Here, I only want SSL in production. (Change as suits your needs)

Code:

 var express = require('express'),
env = process.env.NODE_ENV || 'development';


var forceSsl = function (req, res, next) {
if (req.headers['x-forwarded-proto'] !== 'https') {
return res.redirect(['https://', req.get('Host'), req.url].join(''));
}
return next();
};


app.configure(function () {
if (env === 'production') {
app.use(forceSsl);
}


// other configurations etc for express go here...
});

Note for SailsJS (0.10.x) users. You can simply create a policy (enforceSsl.js) inside api/policies:

module.exports = function (req, res, next) {
'use strict';
if ((req.headers['x-forwarded-proto'] !== 'https') && (process.env.NODE_ENV === 'production')) {
return res.redirect([
'https://',
req.get('Host'),
req.url
].join(''));
} else {
next();
}
};

Then reference from config/policies.js along with any other policies, e.g:

'*': ['authenticated', 'enforceSsl']

If you are using cloudflare.com as CDN in combination with heroku, you can enable automatic ssl redirect within cloudflare easily like this:

  1. Login and go to your dashboard

  2. Select Page Rules

    Select Page Rules

  3. Add your domain, e.g. www.example.com and switch always use https to on Switch always use https to on

If you want to test out the x-forwarded-proto header on your localhost, you can use nginx to setup a vhost file that proxies all of the requests to your node app. Your nginx vhost config file might look like this

NginX

server {
listen 80;
listen 443;


server_name dummy.com;


ssl on;
ssl_certificate     /absolute/path/to/public.pem;
ssl_certificate_key /absolute/path/to/private.pem;


access_log /var/log/nginx/dummy-access.log;
error_log /var/log/nginx/dummy-error.log debug;


# node
location / {
proxy_pass http://127.0.0.1:3000/;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}

The important bits here are that you are proxying all requests to localhost port 3000 (this is where your node app is running) and you are setting up a bunch of headers including X-Forwarded-Proto

Then in your app detect that header as usual

Express

var app = express()
.use(function (req, res, next) {
if (req.header('x-forwarded-proto') == 'http') {
res.redirect(301, 'https://' + 'dummy.com' + req.url)
return
}
next()
})

Koa

var app = koa()
app.use(function* (next) {
if (this.request.headers['x-forwarded-proto'] == 'http') {
this.response.redirect('https://' + 'dummy.com' + this.request.url)
return
}
yield next
})

Hosts

Finally you have to add this line to your hosts file

127.0.0.1 dummy.com

Loopback users can use a slightly adapted version of arcseldon answer as middleware:

server/middleware/forcessl.js

module.exports = function() {  
return function forceSSL(req, res, next) {
var FORCE_HTTPS = process.env.FORCE_HTTPS || false;
if (req.headers['x-forwarded-proto'] !== 'https' && FORCE_HTTPS) {
return res.redirect(['https://', req.get('Host'), req.url].join(''));
}
next();
};
};

server/server.js

var forceSSL = require('./middleware/forcessl.js');
app.use(forceSSL());

The accepted answer has a hardcoded domain in it, which isn't too good if you have the same code on several domains (eg: dev-yourapp.com, test-yourapp.com, yourapp.com).

Use this instead:

/* Redirect http to https */
app.get("*", function (req, res, next) {


if ("https" !== req.headers["x-forwarded-proto"] && "production" === process.env.NODE_ENV) {
res.redirect("https://" + req.hostname + req.url);
} else {
// Continue to other routes if we're not redirecting
next();
}


});

https://blog.mako.ai/2016/03/30/redirect-http-to-https-on-heroku-and-node-generally/

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

This is a more Express specific way to do this.

app.enable('trust proxy');
app.use('*', (req, res, next) => {
if (req.secure) {
return next();
}
res.redirect(`https://${req.hostname}${req.url}`);
});

You should take a look at heroku-ssl-redirect. It works like a charm!

var sslRedirect = require('heroku-ssl-redirect');
var express = require('express');
var app = express();


// enable ssl redirect
app.use(sslRedirect());


app.get('/', function(req, res){
res.send('hello world');
});


app.listen(3000);

With app.use and dynamic url. Works both localy and on Heroku for me

app.use(function (req, res, next) {
if (req.header('x-forwarded-proto') === 'http') {
res.redirect(301, 'https://' + req.hostname + req.url);
return
}
next()
});

I am using Vue, Heroku and had same problem :

I updated my server.js as below, and i am not touching it anymore because it is working :) :

const serveStatic = require('serve-static')
const sts = require('strict-transport-security');
const path = require('path')


var express = require("express");


require("dotenv").config();
var history = require("connect-history-api-fallback");


const app = express()
const globalSTS = sts.getSTS({'max-age':{'days': 365}});
app.use(globalSTS);


app.use(
history({
verbose: true
})
);


app.use((req, res, next) => {
if (req.header('x-forwarded-proto') !== 'https') {
res.redirect(`https://${req.header('host')}${req.url}`)
} else {
next();
}
});


app.use('/', serveStatic(path.join(__dirname, '/dist')));
app.get(/.*/, function (req, res) {
res.sendFile(path.join(__dirname, '/dist/index.html'))
})


const port = process.env.PORT || 8080
app.listen(port)
console.log(`app is listening on port: ${port}`)