ローカル CA の続きです。
作業ディレクトリを用意
ファイルが増えるかもしれないので適当な場所に作成。local-https にしておく。
サーバー用の証明書作成
cd local-httpsmkcert test1.local作業ディレクトリに test1.local.pem と test1.local-key.pem が作られる。
動作確認
使いまわし用の index.html を作成。
<!DOCTYPE html><meta charset="UTF-8" /><title>Local HTTPS</title><body> <p>test</p></body>VSCode + Live Server
.vscode/settings.json を作成して以下のように書き足す。cert と key はフルパスで、VSCode から見た場所。
{ "liveServer.settings.https": { "enable": true, "cert": "/path/to/local-https/test1.local.pem", "key": "/path/to/local-https/test1.local-key.pem", "passphrase": "" }}現在のディレクトリはこんな感じ。
local-https├── .vscode│ └── settings.json├── index.html├── test1.local-key.pem└── test1.local.pemおもむろに Live Server を起動。起動できない場合(ボタンを押しても無反応)、たぶん cert と key のパスが間違っている。エラー吐くとか何か言ってくれよ!
起動したら https://test1.local:5500/ を開く。鍵アイコンが見えれば成功!
VSCode + Live Server + PHP Server
さらに、PHP のビルトインサーバーも HTTPS で開いてしまう。
まずは適当な index.php を作成。
<?phpphpinfo();ビルトインサーバーを起動しておく。
php -S localhost:9999 index.phpLive Server をプロキシにするため settings.json に追記。
{ "liveServer.settings.https": { "enable": true, "cert": "/path/to/local-https/test1.local.pem", "key": "/path/to/local-https/test1.local-key.pem", "passphrase": "" }, // 以下追記 "liveServer.settings.proxy": { "enable": true, "baseUri": "/", "proxyUri": "http://localhost:9999" }}Live Server を再起動し、https://test1.local:5500/ を開く。鍵アイコンかつ phpinfo() の内容が見えていれば成功!
自前サーバー(Node.js)
Live Server を経由しない場合の例。index.mjs を作成。
import https from "https";import fs from "fs";
const options = { key: fs.readFileSync("./test1.local-key.pem"), cert: fs.readFileSync("./test1.local.pem"),};
/** @type {import("http").RequestListener} */const app = (req, res) => { res.writeHead(200); res.end(fs.readFileSync("./index.html"));};
https.createServer(options, app).listen(9990, "127.0.0.1");起動しておく。
node index.mjshttps://test1.local:9990 を開き、鍵アイコンと最初に作った index.html が見えていれば成功!
おわり
最終的なディレクトリはこんな感じになった。
local-https├── .vscode│ └── settings.json├── index.html├── index.mjs├── index.php├── test1.local-key.pem└── test1.local.pem正直 VSCode + Live Server で十分な気もするけど、いちおう続きがある。→ Caddy でリバースプロキシ