Files
cpp-httplib/docs-src/pages/ja/cookbook/s04-static-files.md
yhirose 0fa4912891 Fix broken relative links in cookbook docs (Fix #2490)
Cookbook body links referenced sibling pages with a bare slug
(e.g. `c14-keep-alive`). Under the pretty-URL layout each page lives
in its own directory, so these resolve against the page's own
directory and 404. Prefix them with `../` to match the convention
already used in the tour and llm-app sections.

Verified clean with `docs-gen check`.
2026-07-08 22:45:29 -04:00

2.2 KiB

title, order, status
title order status
S04. 静的ファイルサーバーを設定する 23 draft

HTML、CSS、画像などの静的ファイルを配信したいときは、set_mount_point()を使います。URLパスとローカルディレクトリを結びつけるだけで、そのディレクトリの中身がまるごと配信されます。

基本の使い方

httplib::Server svr;
svr.set_mount_point("/", "./public");
svr.listen("0.0.0.0", 8080);

./public/index.htmlhttp://localhost:8080/index.htmlで、./public/css/style.csshttp://localhost:8080/css/style.cssでアクセスできます。ディレクトリ構造がそのままURLに反映されます。

複数のマウントポイント

マウントポイントは複数登録できます。

svr.set_mount_point("/", "./public");
svr.set_mount_point("/assets", "./dist/assets");
svr.set_mount_point("/uploads", "./var/uploads");

同じパスに複数のマウントを登録することもできます。その場合は登録順に探されて、見つかった最初のものが返ります。

APIハンドラと組み合わせる

静的ファイルとAPIハンドラは共存できます。Get()などで登録したハンドラが優先され、マッチしなかったときにマウントポイントが探されます。

svr.Get("/api/users", [](const auto &req, auto &res) {
  res.set_content("[]", "application/json");
});

svr.set_mount_point("/", "./public");

これでSPAのように、/api/*はハンドラで、それ以外は./public/から配信、という構成が作れます。

MIMEタイプを追加する

拡張子からContent-Typeを決めるマッピングは組み込みですが、カスタムの拡張子を追加できます。

svr.set_file_extension_and_mimetype_mapping("wasm", "application/wasm");

Warning: 静的ファイル配信系のメソッドはスレッドセーフではありません。起動後(listen()以降)には呼ばないでください。起動前にまとめて設定しましょう。

ダウンロード用のレスポンスを返したい場合はS06. ファイルダウンロードレスポンスを返すも参考になります。