Skip to content

Astro Starlightをサブディレクトリ内にて完結させる

※本記事は2025/03/13時点のもので、将来的にAstro Starlight側で本対応される?

やりたいこと

  • https://example.com/sampleにアクセスした際に、Astro Starlightのトップページが表示されるようにする
  • サブディレクトリ配下にて完結させる

そもそもなぜこんなことをしようかと思ったのか

このWebサイトは以下のようなディレクトリ構成で動いている

www.koba-masa.com
├ project1 ・・・ Reactにて管理
├ sample ・・・ Astro StarLightにて管理
│ ├ techniques
│ │ └ astro-starlight-subdirectory
│ │ └ index.html
│ └ index.html
└ index.html ・・・ Astroにて管理

それを以下のようなAWS環境で動かしている

インフラ構成図

要は管理しているアプリケーションごとに異なるS3バケットに配置し、それをCloudFrontのビヘイビアによって振り分けている
これらを適切に振り分けるには共通的なプレフィックスが必要となるので、サブディレクトリ配下で完結するようにしなくてはならないというのが背景となる

公式ドキュメント的には

Starlightのすべてのページをサブパスに追加するには、ドキュメントのコンテンツをsrc/content/sample/のサブディレクトリに配置します。

たとえば、Starlightのページがすべて/guides/で始まる場合は、コンテンツをsrc/content/sample/guides/ディレクトリに追加します。

公式ドキュメント側にはこの記載されており、その通りに実装しても今回の要件は満たせない※目的が異なる

公式ドキュメント通りに配置

content配下は以下のようになっている

Terminal window
% find src/content
src/content
src/content/sample
src/content/sample/sample
src/content/sample/sample/index.mdx

ビルドした結果をみると、以下のようになっている

Terminal window
dist
dist/pagefind
dist/pagefind/pagefind.en_c6372dd1c5.pf_meta
(省略)
dist/pagefind/pagefind.js
dist/404.html
dist/sample
dist/sample/index.html
dist/_astro
dist/_astro/Search.astro_astro_type_script_index_0_lang.18-vQxR-.js
(省略)
dist/_astro/houston.CZZyCf7p_1Lnsdn.webp
dist/_astro/Code.B9nJ75bs.css
dist/favicon.svg

https://example.com/sampleにアクセスした際にトップページが表示されるようになるが、サブディレクトリ内で完結しているとは言えない

サブディレクトリ内で完結させる

astro.config.mjsに以下のような設定を追加する

export default defineConfig({
base: '/sample',
outDir: `./dist/sample`,
integrations: [
starlight({})
]
})

content配下は以下のようにする。サブディレクトリは作成しない

Terminal window
% find src/content
src/content
src/content/sample
src/content/sample/index.mdx

この状態でビルドすると以下のようになる

Terminal window
dist
dist/sample
dist/sample/index.html
dist/sample/pagefind
dist/sample/pagefind/pagefind-modular-ui.js
(省略)
dist/sample/pagefind/pagefind.js
dist/sample/404.html
dist/sample/_astro
dist/sample/_astro/astro-starlight-subdirectory.ltnQ_7Wo_Mgv0R.webp
(省略)
dist/sample/_astro/Code.B9nJ75bs.css
dist/sample/favicon.svg

結論

  • ビルド時の出力先を変更する
  • Astro Starlight側の変更は不要である

参考


(自分で書いた文章だけど、読みづらいな。。。)