Amazon’s S3 is a great, cheap way to host your static site. But if you’re moving over an old site, especially if you’re importing a site from a content management system, you might want or need to change your URL scheme. While it’s not as easy to find in the S3 documentation, it’s actually quite easy.

Let’s start simple. Say we have a site that has a number of articles that were posted as www.domain.com/posts/this-is-the-slug. As we switch to S3 we’d like to change that to www.domain.com/blog/this-is-the-slug.

First you’ll need to create a set of rules for the content. In this case it would look something like:

<RoutingRules>
	<RoutingRule>
		<Condition>
			<KeyPrefixEquals>posts/</KeyPrefixEquals>
		</Condition>
		<Redirect>
			<ReplaceKeyPrefixWith>blog/</ReplaceKeyPrefixWith>
		</Redirect>
	</RoutingRule>
</RoutingRules>

So where does this go? Log into S3 and find your bucket. Click on Properties (upper right) and expand ‘Static Website Hosting’. From there expand ‘Edit Redirection Rules’. Paste the rules in the textarea.

S3 Redirection Rules

Ok. So what about something slightly more complicated? Say we’re starting with the same URL scheme: www.domain.com/posts/this-is-the-slug/. This time, instead of just universally changing posts to blog, we want to change the URL to www.domain.com/blog/this-is-the-slug.html. Still pretty easy:

<RoutingRules>
	<RoutingRule>
		<Condition>
			<KeyPrefixEquals>posts/</KeyPrefixEquals>
		</Condition>
		<Redirect>
			<ReplaceKeyPrefixWith>blog/</ReplaceKeyPrefixWith>
		</Redirect>
		<RoutingRule>
        <Condition>
            <KeyPrefixEquals>this-is-the-slug</KeyPrefixEquals>
        </Condition>
        <Redirect>
            <ReplaceKeyPrefixWith>this-is-the-slug.html</ReplaceKeyPrefixWith>
        </Redirect>
    </RoutingRule>
	</RoutingRule>
</RoutingRules>

You can do more advanced matching by hostname, protocol, specifying the redirect code, etc. To my knowledge you can’t use regex in the rules, but I plan on testing that soon.