Creating an S3 Website Redirect from the CLI

2 minute read

A quick one today — creating S3 Static Website Hosting redirects with the AWS CLI. Clients often want to have www.example.com redirect to example.com or vice versa. Why? Because SEO. I suspect “SEO” is smart enough recognize one site with two URLs, but hey, I just work here.

It’s easy enough to do this sort of thing in Apache or NGINX. However, if the real site is in AWS, especially CloudFront, I like the simplicity and single purposeness of using S3 Static Website hosting to for redirects. To set this up you create an S3 bucket, enable static web hosting, turn on Redirect requests and give it the domain you want to redirect to. Done.

But, I’m lazy, I don’t like logging in to the AWS console (because I use MFA and so should you), and these tend to come in batches where the client not only wants a www redirect but has also registered a bunch of other random domains/TLDs, because SEO.

Fortunately, these buckets can be setup via the AWS CLI interface.

The first step is to create empty bucket. That’s easy:

aws s3api create-bucket --bucket www.example.com --region us-east-1

The trick, if you want to call it that, is that the bucket name must match the DNS name that will point to it. Any other name won’t work.

The second step is to add the redirection configuration. This is a blob of JSON that’s loaded from a file. That file should look like:

{
    "RedirectAllRequestsTo": {
        "HostName": "example.com"
    }
}

Let’s call it example-redirect.json.

There a CLI command, put-bucket-website, just for applying this:

aws s3api put-bucket-website --bucket www.example.com --website-configuration file://example-redirect.json

I know what you’re thinking. You’re thinking “This is a stupid post, it’s way easier to log in to the console than it is to create the JSON file.”. And, you’d be correct. To be easier, that step has to be taken care of automatically, and it can be with a bit of scripting magic:

aws_redirect() {
    aws s3api create-bucket --bucket $1 --region us-east-1

    local json_file=`mktemp`
    printf '{"RedirectAllRequestsTo":{"HostName": "%s"}}\n' $2 > $json_file

    aws s3api put-bucket-website --bucket $1 --website-configuration file://$json_file

    rm $json_file
}

Most of this should be obvious, the script takes two arguments, the site to redirect (which becomes $1) and where to redirect to ($2). The only tricky bit is creating the file of JSON. I use mktemp to generate a randomly named temp file. This avoids conflicts and security issues that could arise if the name wasn’t random (unlikely on your personal machine, but hey, why not do it right?). I use printf to generate it’s content, so I don’t have to mess around escaping double quotes. Boom.

So, we’re down to:

aws_redirect www.example.com example.com

and that’s way easier than logging in to the AWS console.

Of course, there’s still DNS setup, but that’s another post.

Tags: , ,

Updated:

Comments