Proxy Server
const http = require('http');
const https = require('https');
const fs = require('fs');
function createProxyServer(port, targetUrl, certificatePath, privateKeyPath) {
// Read the SSL certificate and private key files
const certificate = fs.readFileSync(certificatePath);
const privateKey = fs.readFileSync(privateKeyPath);
// Create the HTTPS options using the certificate and private key
const httpsOptions = {
cert: certificate,
key: privateKey
};
// Create the HTTP server
const httpServer = http.createServer((req, res) => {
// Redirect the request to the target server
const options = {
hostname: targetUrl,
port: 80,
path: req.url,
method: req.method,
headers: req.headers
};
const proxyReq = http.request(options, (proxyRes) => {
// Forward the response from the target server to the client
res.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.pipe(res);
});
req.pipe(proxyReq);
});
// Create the HTTPS server
const httpsServer = https.createServer(httpsOptions, (req, res) => {
// Redirect the request to the target server
const options = {
hostname: targetUrl,
port: 443,
path: req.url,
method: req.method,
headers: req.headers
};
const proxyReq = https.request(options, (proxyRes) => {
// Forward the response from the target server to the client
res.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.pipe(res);
});
req.pipe(proxyReq);
});
// Start the HTTP and HTTPS servers
httpServer.listen(port, () => {
console.log(`HTTP proxy server running on port ${port}`);
});
httpsServer.listen(port + 1, () => {
console.log(`HTTPS proxy server running on port ${port + 1}`);
});
}
// Usage Example for createProxyServer
// Specify the port number, target URL, SSL certificate path, and private key path
const port = 8080;
const targetUrl = 'http://example.com';
const certificatePath = '/path/to/certificate.pem';
const privateKeyPath = '/path/to/privatekey.pem';
// Create the proxy server
createProxyServer(port, targetUrl, certificatePath, privateKeyPath);
I hope this post was helpful to you.
Leave a reaction if you liked this post!