开发者

Can I configure expressjs to serve some pages over http and others over https?

开发者 https://www.devze.com 2023-02-14 00:47 出处:网络
Based on the response to this question: How do I configure nodejs/expressjs to serve pages over https?

Based on the response to this question:

How do I configure nodejs/expressjs to serve pages over https?

I've been trying to set up the equivalent of:

var express = require('express');
var fs = require("fs");
var crypto = r开发者_如何学运维equire('crypto');

var app = express.createServer();
var appSecure = express.createServer();
var privateKey = fs.readFileSync('privatekey.pem').toString();
var certificate = fs.readFileSync('certificate.pem').toString();
var credentials = crypto.createCredentials({key: privateKey, cert: certificate});
appSecure.setSecure(credentials);


app.get('/secretStuff', function(req,res) {
//redirect to https
}

appSecure.get('/secretStuff', function(req, res) {
//show you the secret stuff
}

Is this something that's doable with the current release of expressjs and node 2.4?


Yes, this can be done and it looks like you already have most of what you need. Just send the redirect in your app.get handler

app.get('/secretStuff', function(req,res) {
  res.redirect('https://' + req.header('Host') + req.url);
}

Also make sure you do something like app.listen(80) and appSecure.listen(443) to actually start the servers on the appropriate port. Otherwise be sure to construct the HTTPS URL with the correct port. For production, this thing is typically handled outside of your app server (node.js) with a reverse proxy like nginx. It is trivial to do this in nginx which will let your node.js process run as non-root and remove the need to have clients directly connecting to node.js, which is not as battle-hardened as nginx for serving live internect TCP connections (I'm paraphrasing Ryan Dahl himself here).


You can only serve a web page over the connection that the request came in. If the request did not come in over https, you can't send the response that way.

So, first you have to be listening for both http and https requests. If a request comes in over http that you want to answer over a secure connection, do not do any processing but immediately redirect it to an https url. Then when the client reissues the request, process as normally.

If the framework uses JSGI then you can probably use the redirect module from Jack otherwise you will have to do it yourself. The details are at the link, i.e. response code 301 and Location: header with the https URL.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号