Feedback? See Mastodon cross-post.

Context

  • You are using AWS S3 in static website hosting mode.
  • You have some URLs on your static site that you want returned as 3xx redirects.
  • You want to use x-amz-website-redirect-location S3 object metadata item to implement these HTTP redirects (documentation).

Problem

  • But the tool you are using (perhaps a static site generator like Hugo or Jekyll) does not have a built-in way to set up these S3 redirects.

Solution

  • Store your redirects as files in the local filesystem, that will correspond to the objects in S3.
  • Have the content of each file be the location of the redirect.
  • Use the following zsh script (or your own version of it) to syncrhonise the local information to S3.
  • The script used the AWS CLI and the aws s3api put-object command to set the x-amz-website-redirect-location metadata item.
  • Note regarding redirecting a directory: you will need to use an index.html trick (or whatever your index document is), see below.

sync-s3-redirects.zsh:

#!/bin/zsh

set -e

function processRedirects() {
  cd $1
  bucketname=$2
  for f in **/* ; do
    if [[ -f $f ]]; then
      aws s3api put-object --output text --no-paginate \
        --bucket ${bucketname} \
        --key "$f" --body "$f" \
        --website-redirect-location "$(<"${f}")" 
    fi
  done
}

echo "Syncing S3 redirects"
processRedirects "$1" "$2"

Simple Example

  • Create files corresponding to the redirects as per the following table.
  • If the original URL is a directory (i.e. it ends in a / slash), you will need to put your redirect in a file names index.html under the directory in quesstion
FilenameFile contentsIntent
oldfile.html/newfile.htmlRedirect an old file to new one.
old/file.html/new/file.htmlRedirect an old file to new one.
/olddir/index.html/newdir/Redirect /olddir/ to /newdir/
  • Run the above script: sync-s3-redirects.zsh . BUCKETNAME

Hugo Example

  • Create a sibling directory to your existing Hugo static directory, for example named static-redirects.
  • Fill the new directory with the redirect files, similar to the table above.
  • Edit your Hugo configuration (e.g. hugo.yaml) with a staticDir section like so:
staticDir:
  - static
  - static-redirects
  • Run the script after Hugo’s deploy command:
; hugo deploy
; sync-s3-redirects.zsh static-redirects BUCKETNAME