Skip to content

Instantly share code, notes, and snippets.

@vfeskov
Last active January 3, 2018 19:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vfeskov/21832ac378ffe366b4b7206ec8eaf0c1 to your computer and use it in GitHub Desktop.
Save vfeskov/21832ac378ffe366b4b7206ec8eaf0c1 to your computer and use it in GitHub Desktop.
Redirecting HTTP to HTTPS in Node.js
// *.pem files were generated with:
// openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -nodes -days 365
const http = require('http')
const https = require('https')
const fs = require('fs')
http.createServer((req, res) => {
res.writeHead(301, { Location: `https://localhost${req.url}` })
res.end()
}).listen(80)
const options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
}
https.createServer(options, (req, res) => {
res.writeHead(200)
res.end('Works!')
}).listen(443)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment