3
2

More than 1 year has passed since last update.

ブログサイトをAWSで公開する

Last updated at Posted at 2022-07-17
  • ブログサイトの公開方法は、GitHub Pages やその他無料サービスなどあるようですが、
    ここではAWSを使ってブログサイトを公開する方法を紹介します。
  • AWSを使う理由は、自由度の高さと運用費用の安さです。
  • AWS利用開始1年未満であれば無料枠で運用できますし、1年経過後でも月額10円未満程度で運用できます。

この記事の目的

👇これより先は下記記事の内容を前提とします

導入手順

デプロイの効率化

サイトをビルドし、S3へアップロードする処理をpythonで作成しました。

deploy.py

deploy.py
import os
import subprocess
import boto3
import pathlib

def clear_before():
    s3 = boto3.client('s3')
    bucket_name = "your.bucket.name"
    response = s3.list_objects_v2(Bucket=bucket_name, Prefix="docusaurus/")
    if 'Contents' in response:
      contents = response['Contents']
      for content in contents:
        print("delete:" + content['Key'])
        s3.delete_object(Bucket=bucket_name,Key=content['Key'])

def upload(prefix,file):
    print("filename:" + file.name)
    #print(file.name.split(".")[-1])
    ext = file.name.split(".")[-1]
    content_type="text/html"
    if ext == "txt":
      content_type="text/plain"
    elif ext == "ico":
      content_type="image/x-icon"
    elif ext == "svg":
      content_type="image/svg+xml"
    elif ext == "js":
      content_type="application/javascript"
    elif ext == "css":
      content_type="text/css"
    print("content_type:" + content_type)
    s3 = boto3.client('s3')
    
    key_value = file.name
    if(len(prefix)):
      key_value = prefix + "/" + file.name
    
    with open(file, 'rb') as f:
        res = s3.put_object(
            Body=f,
            Bucket="your.bucket.name",
            Key=key_value,
            ContentType=content_type,
        )

if __name__ == '__main__':
    cmd = ["npm", "run", "build"]
    subprocess.run(cmd,cwd=".",shell=True)

    clear_before()

    files = pathlib.Path("build").glob("**/*")
    for file in files:
      if pathlib.Path.is_file(file):
        dir_prefix = "docusaurus/" + str(file.parent).replace("\\","/")[len("build/"):]
        if dir_prefix.endswith('/'):
          dir_prefix = dir_prefix[:-1]
        upload(dir_prefix,file)

index.html参照エラーの回避

CloudFrontでDocusaurusのサイトを公開すると、index.htmlが参照できないことにより、画面遷移の際に画面表示エラーが発生します。
image

AWSからもこの問題に対する解決方法が公開されています。
index.html を追加してファイル名を含まない URL をリクエストする

具体的手順を以下に記載します。

Lambdaの作成

CloudFrontへ適用するLambda関数はバージニア北部リージョンで作成する必要があります。
lambda_function.py

lambda_function.py
import json

def lambda_handler(event, context):
    request = event['Records'][0]['cf']['request']
    print(request['uri'])
    
    if request['uri'].endswith("/"):
        request['uri'] += "index.html"
        print(request['uri'])
    elif not '.' in request['uri']:
        request['uri'] += "/index.html"
        print(request['uri'])
        
    return request

CloudFrontへの適用

Lambda関数のコンソールから、Lambda@Edge へのデプロイを指定します。
image

Lambda@Edge へのデプロイ。
image

👇前提記事

👇関連記事

👇参考URL

3
2
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
3
2