1
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 3 years have passed since last update.

nuxtで作成したSPAをs3ホスティングし、cloudfront + lambda@edgeでbasic認証をかけて配信する

Posted at

タイトルの通り。

nuxt

% npx create-nuxt-app app

SPAなので以下のあたりの設定になります。
他はお好みで。僕はtypescriptを使います。typescriptしか勝たん。

> ? Rendering mode: Single Page App
> ? Deployment target: Static (Static/JAMStack hosting)
% cd app
% npm run build
% npm run generate

generateを実行すると、デフォルトだと dist/ とその中にファイル群が生成されます。

s3

適当にバケットを作成でOK
アクセスも全てプライベートでOK
静的ウェブサイトホスティングも無効のままでOK

dist/ の中身を直下に全てアップします。

cloudfront

ディストリビューションの作成

  • Origin domain: 先ほど作ったs3バケット
  • s3ののアクセス: OAIを新規に作成( Create new OAI )してそれを利用。バケットポリシーのアップデートをする。(以下の画像の状態)

スクリーンショット 2021-07-20 12.13.46.png

  • Viewer protocol policy: Redirect HTTP to HTTPS
  • Allowed HTTP methods: GET, HEAD, OPTIONS, PUT, POST, PATCH, DELETE
  • その他は全てそのままでOK

lambda@edge

nuxtのルーティング用とbasic認証用で2つ用意する

参考: Lambda@Edge イベント構造

import re

def lambda_handler(event, context):
    suffix = '/index.html'
    append_to_dirs = 'index.html'

    # e.g.) "/some/page" but not "/", "/some/" or "/some.jpg"
    regex_suffixless = r'^/(?=.+)(?!.+\..+$)(?!.*/$).*$'

    # e.g. "/some/" or "/some/page/" but not root "/"
    regex_trailing_slash = r'^.+/$'

    request = event["Records"][0]["cf"]["request"]
    uri = request["uri"]

    if suffix and re.match(regex_suffixless, uri):
        request["uri"] = uri + suffix
        return request

    if append_to_dirs and re.match(regex_trailing_slash, uri):
        request["uri"] = uri + append_to_dirs
        return request

    return request

これでSPAにbasic認証をかけて周りに共有することができた。
(今回はIP制限かけられない縛りでこの方法をとってみた)

1
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
1
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?