Last active
May 31, 2019 09:54
-
-
Save lequanghuylc/b858393dc3dd1f3dd3b67e07c189f42c to your computer and use it in GitHub Desktop.
Api gateway nodejs multiport http https #nodejs
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
const express = require('express'); | |
const proxy = require('http-proxy-middleware'); | |
const fs = require("fs"); | |
const { createServer } = require('https'); | |
const certOptions = { | |
key: fs.readFileSync('/etc/letsencrypt/live/s1.example.com/privkey.pem'), | |
cert: fs.readFileSync('/etc/letsencrypt/live/s1.example.com/fullchain.pem'), | |
}; | |
const mainSystem = express(); | |
// support https | |
createServer(certOptions, mainSystem).listen(443, (err) => { | |
if (err) throw err; | |
console.log('> Ready on https://example.com'); | |
}); | |
// redirect to https | |
mainSystem.use(function(req, res, next) { | |
if (req.secure) { | |
// request was via https, so do no special handling | |
next(); | |
} | |
else { | |
// request was via http, so redirect to https | |
// res.redirect('https://' + req.headers.host + req.url); | |
} | |
}); | |
mainSystem.use('*', (req, res, next) => { | |
switch (req.headers.host) { | |
case 'example.com': // like nextjs | |
proxy({ target: 'http://localhost:portweb', changeOrigin: true })(req, res, next); | |
break; | |
case 's1.example.com': // backend microservice 01, with websocket | |
proxy({ target: 'http://localhost:port01', changeOrigin: true, ws: true })(req, res, next); | |
break; | |
case 's2.dev.houselink.info': // backend microservice 01, with websocket | |
proxy({ target: 'http://localhost:port02', changeOrigin: true, ws: true })(req, res, next); | |
break; | |
default: | |
proxy({ target: 'http://localhost:portweb', changeOrigin: true })(req, res, next); | |
} | |
}); | |
mainSystem.listen(80); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment