Skip to content

Instantly share code, notes, and snippets.

@chulman444
Last active June 25, 2020 11:14
Show Gist options
  • Save chulman444/9dc923abeb5f2072fdd9582d15fc38f7 to your computer and use it in GitHub Desktop.
Save chulman444/9dc923abeb5f2072fdd9582d15fc38f7 to your computer and use it in GitHub Desktop.
Express app redirect http to https.
/**
* Install express and create a directory `sslcert/`
*
* > npm i express
* > mkdir sslcert
*
* Create https key and cert
*
* > openssl req -nodes -new -x509 -keyout sslcert/server.key -out sslcert/server.cert
* > # Just Enter through the prompts
*
* To run the server:
*
* > sudo node index.js
*
* Visit https://localhost
*
* Then visit http://localhost and see that `"Redirecting"` message is printed.
*/
const express = require("express")
const http = require("http")
const https = require("https")
const fs = require("fs")
async function main() {
const key = fs.readFileSync("./sslcert/server.key", "utf-8")
const cert = fs.readFileSync("./sslcert/server.cert", "utf-8")
const https_cred = { key, cert }
const request_handler = getRequestHandler()
const redirect_handler = getRedirectHandler()
const app = https.createServer(https_cred, request_handler)
const redirect_app = http.createServer(redirect_handler)
app.listen(443, () => console.log("APP running"))
redirect_app.listen(80, () => console.log("Redirect running"))
}
function getRequestHandler() {
const app = express()
app.get("/", (req,res) => res.send('hi'))
return app
}
function getRedirectHandler() {
const app = express()
// app.all("*", (req, res) => {
app.use((req, res, next) => {
console.log("Redirecting")
res.redirect('https://' + req.headers.host + req.url);
})
return app
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment