Module 0329: Node Express + HTTPS + Apache2
Tak Auyeung, Ph.D.
February 16, 2020
Contents
1 About this module
- Prerequisites:
- Objectives: This module presents a solution to get Node Express to work with Apache2 and serve through HTTPS.
2 Apache2 configuration
In Apache2, inside the section corresponding to VirtualHost section for port 443, add a few proxy related entries:
ProxyRequests off # disable forward proxy <Proxy *> Order deny,allow # unless specified, do not proxy Allow from all # to enable any request to access proxy server SSLProxyEngine on # to enable SSL via Proxy </Proxy> <Location /abc/def/> ProxyPass https://localhost:12345/ ProxyPassReverse https://localhost:12345/ </Location>
This configuration specifically turn off forward proxy. Forward proxy requires clients (browsers) to be configured as
well. However, its security implications are far reaching and it is not needed for serving pages via HTTPS and
Express.
A reverse proxy, such as what we are trying to accomplish here, is to allow the following traffic pattern:
- Apache accepts a (HTTPS) connection.
- Based on the URL, Apache figures that it (Apache) is not to serve the content.
- Instead, Apache relies on ProxyPass and ProxyPassReverse to figure out what server (in the form of an URIL) is
actually responsible.
- The client (browser) is completely oblivious to this process.
- In our example, any thing with the URL of https://originalserver/abb/def/ is automatically relayed to
https://localhost:12345/.
- The directive ProxyPassReverse is necessary to help rewrite HTTP response headers.
3 Localhost certificate
Because we are using SSL between Apache and the localhost server, it is necessary to set up the localhost SSL certificate. This is
done via the instructions at https://github.com/sagardere/set-up-SSL-in-nodejs.
4 Express code
The following is the code of the Express middleware:
const fs = require(’fs’) const https = require(’https’) const express = require(’express’) const app = express() const privateKey = fs.readFileSync(’localhost.key’,’utf8’) const certificate = fs.readFileSync(’localhost.crt’,’utf8’) const credentials = { key: privateKey, cert: certificate } app.get(’/’, function (req, res) { res.send(’hello␣world’) } ) var httpsServer = https.createServer(credentials, app) httpsServer.listen(12345)
This code can reside anywhere. This code, when run, creates a middleware process that listens to port 12345 of localhost. End
points can then be set up to serve the intended pages.
Note that this code can be automatically started using cron.