ローカル HTTPS サーバー

ローカル CA の続きです。

作業ディレクトリを用意

ファイルが増えるかもしれないので適当な場所に作成。local-https にしておく。

サーバー用の証明書作成

Terminal window
cd local-https
mkcert test1.local

作業ディレクトリに test1.local.pemtest1.local-key.pem が作られる。

動作確認

使いまわし用の index.html を作成。

index.html
<!DOCTYPE html>
<meta charset="UTF-8" />
<title>Local HTTPS</title>
<body>
<p>test</p>
</body>

VSCode + Live Server

.vscode/settings.json を作成して以下のように書き足す。certkey はフルパスで、VSCode から見た場所。

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": ""
}
}

現在のディレクトリはこんな感じ。

local-https
├── .vscode
│ └── settings.json
├── index.html
├── test1.local-key.pem
└── test1.local.pem

おもむろに Live Server を起動。起動できない場合(ボタンを押しても無反応)、たぶん certkey のパスが間違っている。エラー吐くとか何か言ってくれよ!

起動したら https://test1.local:5500/ を開く。鍵アイコンが見えれば成功!

VSCode + Live Server + PHP Server

さらに、PHP のビルトインサーバーも HTTPS で開いてしまう。

まずは適当な index.php を作成。

index.php
<?php
phpinfo();

ビルトインサーバーを起動しておく。

Terminal window
php -S localhost:9999 index.php

Live 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 を作成。

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");

起動しておく。

Terminal window
node index.mjs

https://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 でリバースプロキシ

参考サイト