until coffee cools
home記事一覧playground

Next.jsをS3に静的ホスティングするときに詰まったこと

2025-05-15

TechNext.jsDynamic Routing

Next.js 静的ホスティング × Dynamic Routingで起きる「[slug].html」問題と trailingSlash 設定

Next.js で dynamic routingを使って静的サイトをビルドし、静的ホスティングサービス(AWS S3)にデプロイした際、「[slug].html」が生成されます。 そしてdynamic routingで生成されたページ(例: /posts/first-post)から別のページへ <Link> コンポーネントなどで遷移しようとすると、403 Access Deniedエラーに遭遇したため、その解決策を残しておきます。

out/
├── posts
│   ├── first-post.html
│   └── second-post.html

/posts/first-post/でアクセスできず、/posts/first-post.html でしかアクセスできない

解決策: next.config.ts にtrailingSlash: true を設定

next.config.tsに次の設定を追加して解決。

// next.config.ts
module.exports = {
  // 他の設定...
  trailingSlash: true,
}

まとめ

App Router で dynamic routing + 静的ホスティングの場合はoutディレクトリの中を要確認