在 Express 上啟用 HTTPS 並使用 Cloudflare TLS 憑證
2024 年 11 月 25 日
雖然現在已經有不少服務讓網站很方便的啟用 HTTPS,但仍遇到要用 Express 搭配 HTTPS 的情況,加上得搭配使用 Cloudflare TLS 憑證,因為我較少用 Cloudflare 的服務,索性就紀錄下整個過程。
產生 TLS 憑證
首件需完成事項就是取得 Cloudlfare TLS 憑證,沒有憑證情況下沒法啟用 HTTPS。因此先登入 Cloudlfare 管理頁面,接著進入 SSL/TLS - 原始伺服器的頁面,點擊建立憑證後按照預設的設定產生憑證即可。提醒一下,你需要在 Cloudflare 先增加域名,這樣它才知道要替哪個域名簽發憑證。順利產生憑證後,可以在頁面裡看到原點憑證與私密金鑰,將兩個內容分別儲存為 cert.pem (憑證) 與 key.pem (金鑰) 待會使用。
設定 Express
接著為了讓 Express 啟用 HTTPS,以及讓它在啟動時載入 TLS 憑證,可以在程式碼中做出調整。本次範例是使用 Remix 框架來實現:
import { createRequestHandler } from '@remix-run/express'
import compression from 'compression'
import express from 'express'
import fs from 'fs-extra'
import https from 'https'
import path from 'path'
import * as build from './build/server/index.js'
const port = 443
const options = {
key: fs.readFileSync(path.resolve('./path/to/key.pem')),
cert: fs.readFileSync(path.resolve('./path/to/cert.pem')),
}
const app = express()
app.disable('x-powered-by')
app.use(compression())
app.use(express.static('build/client'))
app.all('*', createRequestHandler({ build }))
const server = https.createServer(options, app)
server.listen(port, () => {
console.log('server is listening on port 443')
})
上面除了啟用 HTTPS 與載入 TLS 憑證也加上平常用的設定供參考,感謝閱讀!