H3XED
Web Development   Browse Topics

How to Use Amazon S3 Redirect Rules and Example Code

Posted Sep 1, 2016 by Nick Vogt
This is a guide with examples for setting up a simple redirect rule for your Amazon S3 bucket. This rule sends the user to a website and page of your choice when they access a resource that is not found or they do not have permission to access.

Note: For security reasons, Amazon S3 always returns a 403 Forbidden/AccessDenied error (and not a 404 Not Found error) when a user attempts to access something that doesn't exist. See this Stack Overflow answer for more details.


Bucket Properties


Open the Properties for the bucket you want to create redirection rules for.

Step 1
Click "Static Website Hosting":

Amazon S3 Redirect Rules

Step 2
Click "Enable website hosting":

Amazon S3 Redirect Rules

This menu is the same menu you use when you want to host a static website on Amazon S3. It contains the redirection rules.

Step 3
Click "Edit Redirection Rules" to open the text box where you can enter the actual rules:

Amazon S3 Redirect Rules

Note: In order to use redirection rules, you must at least specify an index file. I used index.html, which exists in my bucket and is a simple HTML page for users that try to browse to the root of my bucket.

Step 4
Here you enter the redirection rule. This is a simple rule that sends users to a "notfound" page on a website, and the resource they were trying to access is appended to the end.

<RoutingRules>
    <RoutingRule>
        <Condition>
            <HttpErrorCodeReturnedEquals>403</HttpErrorCodeReturnedEquals>
        </Condition>
        <Redirect>
            <HostName>mywebsite.com</HostName>
            <ReplaceKeyPrefixWith>notfound/</ReplaceKeyPrefixWith>
        </Redirect>
    </RoutingRule>
</RoutingRules>

Amazon S3 Redirect Rules

The ReplaceKeyPrefixWith means it adds "notfound/" as a prefix to the resource they were trying to access. So if they tried to access:

https://s3-myregion.amazonaws.com/mybucket/someresource.jpg
And it didn't exist, they would be redirected to:

http://mywebsite.com/notfound/someresource.jpg
If you don't care about the resource they were trying to access, and just want to send them to a notfound page, you can replace ReplaceKeyPrefixWith with ReplaceKeyWith.

When you're done, be sure to hit "Save"!

More Reading
For full details and options for using Amazon S3 Bucket Redirection Rules, including all available conditions and redirects, view the syntax here.
Share This Post
Facebook Twitter

Comments


Share This Post
Facebook Twitter
H3XED © Nick Vogt   RSS   Privacy Policy   Facebook   Twitter   Google+