0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【S3+CloudFront+Nuxt3】 Access Deniedエラーを回避する方法

0
Posted at

課題

Nuxt3で作成したWebサイトをS3+CloudFrontで配信をした時に、動的ルーティング(/item/[id]のようにURLに含めたパラメータに応じたページにルーティングする仕組み)したページのURLをブラウザに直接入力してアクセスするとAccess Deniedになり、正しく表示ができません。

解決策

この問題は指定されたURLに従ってCloudFrontがS3からコンテンツを配信しようとした時に、配信するページが無いために発生しています。
そこで、対策として配信ページがない場合(つまり、404や403エラーが発生した場合)はトップページを表示させることでNuxtのルーティングが動作するようにすることで解決ができます。

 コンソールから設定する場合

  1. AWS Management Consoleにサインインし、CloudFrontサービスに移動します。
  2. 対象のディストリビューションを選択し、"Error Pages"タブに移動します。
  3. "Create Custom Error Response"ボタンをクリックします。
  4. 404と403エラーのためのカスタムエラーレスポンスをそれぞれ作成します。

スクリーンショット 2023-09-20 22.09.32.png

SAMテンプレートで設定する場合

CloudFrontのDistributionConfig内に下記のように追加します。

CloudFrontDistribution:
  Type: AWS::CloudFront::Distribution
  Properties:
    DistributionConfig:
      ...
      CustomErrorResponses:
        - ErrorCode: 404
          ResponsePagePath: /index.html
          ResponseCode: 200
        - ErrorCode: 403
          ResponsePagePath: /index.html
          ResponseCode: 200

まとめ

Nuxt3で作成したSPAをS3とCloudFrontを使用して配信する際に直面する可能性がある動的ルーティングの問題は、CloudFrontのカスタムエラーレスポンスを適切に設定することで解決できます。

この設定により、存在しないページへのアクセスもトップページにリダイレクトされ、Nuxtのルーティング機能が適切に動作するようになります。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?