Created
October 4, 2016 06:26
-
-
Save cookie-ag/1e1bc89c3572ab18d8a7f6b941656fc5 to your computer and use it in GitHub Desktop.
Sample HTTPS server for Express 4.x
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Create self-signed certificate using: | |
// openssl genrsa 1024 > private.key | |
// openssl req -new -key private.key -out cert.csr | |
// openssl x509 -req -in cert.csr -signkey private.key -out certificate.pem | |
// Key is certificate key and cert.pem is certificate file | |
// 443 is standard for all HTTPS but is not recommended to use as it might be obvious port to attack. | |
var fs = require('fs'); | |
var https = require('https'); | |
var express = require('express'); | |
var app = express(); | |
var httpsPort = 3443; | |
app.set(‘port_https’, httpsPort); | |
//Setup the server | |
https.createServer({ | |
key: fs.readFileSync('key.pem'), | |
cert: fs.readFileSync('cert.pem') | |
}, app).listen(httpsPort); | |
// Redirect all routes to be on HTTPS | |
app.all(‘*’, function(req, res, next){ | |
if (req.secure) { | |
return next(); | |
}; | |
res.redirect(‘https://’+req.hostname+”:”+app.get(‘port_https’)+req.url); | |
}); | |
//Example of sample HTTP GET to test the server | |
app.get('/', function (req, res) { | |
res.header('Content-type', 'text/html'); | |
return res.end('<h1>Hello, Secure World!</h1>'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment