1. Home

Anil

< Blog />

Redirect amazon s3 pages hosted as a static website

in

I use Amazon S3 to host my simpler static websites, it’s simple, cheap and removes all the hassle from administering a web server.

I had to add some redirect rules to redirect some of my posts from my old url format to my new one. This is how I did it.

Go to your S3 bucket console Properties Static website hosting and under Redirection rules (optional) you can enter the following XML rules.

Note

The order the routing rules are entered matter.

In the below example the first route is a blog post we want to match, the last route is a “catch all” 404.

<RoutingRules>
    <!-- Rule #1 Redirect this key prefix to another one via a 301 redirect -->
    <RoutingRule>
        <Condition>
            <KeyPrefixEquals>post/41/slug-for-post</KeyPrefixEquals>
        </Condition>
        <Redirect>
            <Protocol>https</Protocol>
            <HostName>anil.io</HostName>
            <ReplaceKeyWith>blog/category/slug-for-post</ReplaceKeyWith>
            <HttpRedirectCode>301</HttpRedirectCode>
        </Redirect>
    </RoutingRule>

    <!-- Rule #2 - Catch all 403's - redirect to a 404 -->
    <RoutingRule>
        <Condition>
            <HttpErrorCodeReturnedEquals>403</HttpErrorCodeReturnedEquals>
        </Condition>
        <Redirect>
            <Protocol>https</Protocol>
            <HostName>anil.io</HostName>
            <ReplaceKeyWith>404-error-not-found/index.html</ReplaceKeyWith>
        </Redirect>
    </RoutingRule>
</RoutingRules>

Warning

S3 will return a HTTP 403 Forbidden if you don’t have the List Objects permission set for Everyone.

../../../_images/list-objects-permission.png

Ensure your error document key is set correctly (and exists) under Properties Static website hosting.

../../../_images/static-hosting-config.png

Consult the S3 documentation for the entire property list and further explanation.

AWS Documentation