Last active
December 11, 2015 16:09
-
-
Save knpwrs/4626088 to your computer and use it in GitHub Desktop.
This is an example showing how to create an HTTPS server in node. It also listens on HTTP and redirects users to the HTTPS page. You can test this example using self-signed certificates (follow the instructions at https://devcenter.heroku.com/articles/ssl-certificate-self to generate your own self-signed certificates). Tested and working in node…
This file contains hidden or 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
# Dependencies | |
fs = require 'fs' | |
https = require 'https' | |
http = require 'http' | |
# Variables | |
SECURE_PORT = 8443 | |
INSECURE_PORT = 8080 | |
HOST = 'localhost' | |
MESSAGE = 'Hello, Secure World!' | |
# Create https server | |
https.createServer( | |
key: fs.readFileSync 'server.key', 'utf-8' | |
cert: fs.readFileSync 'server.crt', 'utf-8' | |
, (req, res) -> | |
res.writeHead 200, | |
'Content-Type': 'text/plain' | |
'Content-Length': MESSAGE.length | |
res.end MESSAGE | |
).listen SECURE_PORT, HOST | |
# Create http server | |
http.createServer((req, res) -> | |
res.writeHead 301, {'Location': 'https://' + HOST + ':' + SECURE_PORT} | |
res.end(); | |
).listen INSECURE_PORT, HOST |
This file contains hidden or 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
// Dependencies | |
var fs = require('fs'), | |
https = require('https'), | |
http = require('http'); | |
// Variables | |
var SECURE_PORT = 8443, | |
INSECURE_PORT = 8080, | |
HOST = 'localhost', | |
MESSAGE = 'Hello, Secure World!'; | |
// Create https server | |
https.createServer({ | |
key: fs.readFileSync('server.key', 'utf-8'), | |
cert: fs.readFileSync('server.crt', 'utf-8') | |
}, function (req, res) { | |
res.writeHead(200, { | |
'Content-Type': 'text/plain', | |
'Content-Length': MESSAGE.length | |
}); | |
res.end(MESSAGE); | |
}).listen(SECURE_PORT, HOST); | |
// Create http server | |
http.createServer(function (req, res) { | |
res.writeHead(301, {'Location': 'https://' + HOST + ':' + SECURE_PORT}); | |
res.end(); | |
}).listen(INSECURE_PORT, HOST); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment