LoginSignup
6
5

More than 5 years have passed since last update.

AWS(S3+CloudFront)でカスタム404ページの作成

Last updated at Posted at 2018-01-11

サイト全体でのカスタム404設定という要件があったため、AWSコンポーネントのみで対応したときのメモ。

前準備

サイト全体は常時HTTPS対応していたため、CloudFrontでS3のウェブサイトをSSL化するを参考にし、カスタム404ページを配置。
Route53の設定については割愛。

メモ書きのため以下を利用

  • S3 Bucket Name
    • hoge.domain.jp
  • CloudFront Domain Name
    • hogefoo.cloudfront.net
  • 404 Page
    • 404.html

S3設定

Static website hosting

このバケットを使用してウェブサイトをホストするを選択
以下の設定で、S3の

  • インデックスドキュメント
    • 存在しないファイル名にしておく(hoge.htmlとか)
  • エラードキュメント
    • 設定しない
  • リダイレクトルール
    • 以下を記載
<RoutingRules>
  <RoutingRule><!-- S3で存在しないパスを見るとAccessDenied(403) -->
    <Condition>
      <HttpErrorCodeReturnedEquals>403</HttpErrorCodeReturnedEquals>
    </Condition>
    <Redirect>
      <HostName>hogefoo.cloudfront.net</HostName>
      <ReplaceKeyWith/>
    </Redirect>
  </RoutingRule>
  <RoutingRule>
    <Condition><!-- おまじない的に404定義 -->
      <HttpErrorCodeReturnedEquals>404</HttpErrorCodeReturnedEquals>
    </Condition>
    <Redirect>
      <HostName>hogefoo.cloudfront.net</HostName>
      <ReplaceKeyWith/>
    </Redirect>
  </RoutingRule>
</RoutingRules>

CloudFront設定

General

  • Default Root Object
    • 存在しないファイル名にしておく(hoge.htmlとか)
      • こうしておくことで、CloudFrontのRootにアクセス来た際に404になるため。

ErrorPage

Create Custom Error Responseで以下のHTTP Error Code二つを追加する。

  • HTTP Error Code
    • 403: Forbidden
    • 404: Not Found
  • Error Caching Minimum TTL (seconds)
    • 300(default)
  • Customize Error Response
    • Yes
  • Response Page Path
    • /404.html
  • HTTP Response Code
    • 404: Not Found

アクセス

Route53で上記CloudFrontを設定し、アクセスし、Status Codeなどのレスポンスを確認。

Status Code: 404 Not Found
X-Firefox-Spdy: h2
accept-ranges: bytes
age: nnnnn
content-length: nnnn
content-type: text/html
date: Thu, 11 Jan 2018 04:15:23 GMT
etag: "xxxxxxxxxxxxxxxxxxxxx"
last-modified: Wed, 10 Jan 2018 09:50:55 GMT
server: AmazonS3
via: 1.1 hogefoo.cloudfront.net (CloudFront)
x-amz-cf-id: xxxxxxxxxxx_xxxxxxxx==
x-cache: Error from cloudfront
6
5
2

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
6
5