-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproxy.js
55 lines (46 loc) · 1.62 KB
/
proxy.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/* eslint-disable no-console */
import fs from "fs/promises";
import http from "http";
import httpProxy from "http-proxy";
import https from "https";
// Configuration.
const baseDomain = "oathompsonjones.co.uk";
const domainPortMap = {
[baseDomain]: 3000,
[`haskell-graphics.${baseDomain}`]: 3001,
};
// Setup proxy.
const ssl = { cert: null, key: null };
try {
ssl.cert = await fs.readFile(`/etc/letsencrypt/live/${baseDomain}/fullchain.pem`);
ssl.key = await fs.readFile(`/etc/letsencrypt/live/${baseDomain}/privkey.pem`);
} catch (err) {
console.log(`Failed to read SSL certificates: ${err.message}`);
}
const proxy = httpProxy.createProxy({ ssl });
// Setup HTTPS server to proxy requests.
const httpsServer = https.createServer(ssl, (req, res) => {
if (req.headers.host !== undefined) {
for (const [domain, port] of Object.entries(domainPortMap)) {
if ((req.headers.host.startsWith("www.") ? req.headers.host.slice(4) : req.headers.host) === domain)
return proxy.web(req, res, { target: `http://localhost:${port}` });
}
}
return res.end();
});
// Setup HTTP server to redirect to HTTPS.
const httpServer = http.createServer((req, res) => {
if (req.headers.host !== undefined)
res.writeHead(301, { Location: `https://${req.headers.host}${req.url ?? ""}` });
return res.end();
});
// Listen on ports 80 and 443.
try {
httpsServer.listen(443);
console.log("Listening on port 443");
} catch (err) {
console.log(`Failed to listen on port 443: ${err.message}`);
} finally {
httpServer.listen(80);
console.log("Listening on port 80");
}