Put Redirect 301 in S3 or CloudFront hosted website

For a HTTP Redirect to work, if your website is hosted on Amazon S3 or CloudFront, your requisites are:

First, enable the website hosting in your S3 bucket panel.

Pay attention to the Endpoint: {{ bucket }}.s3-website-us-east-1.amazonaws.com, and make this the origin in CloudFront Distribution, and not the default s3 origin: {{ bucket }}.s3.amazonaws.com. If you don’t have this setting ok, redirects wont work with CloudFront.

Second, you have to install AWS CLI, to populate redirects.

Put redirects with aws CLI

Now, you can put redirects:

aws s3api put-object — acl public-read — website-redirect-location “{{ new_url }}" — bucket blog.grippo.com — key “{{ old_url_path }}”

new_url has to be full format with domain, old_url_path is only the path fragment without leading ‘/’. For example:

aws s3api put-object — acl public-read — website-redirect-location “http://blog.grippo.com/2009/07/29/subiendome_a_la_nube_capitulo_dos/index.html" — bucket blog.grippo.com — key “blog/2009/07/subiendome-a-la-nube-capitulo-dos.html”

That’s it. Now, making a GET to the old url will get a redirect:

curl -v blog.grippo.com/blog/2009/07/subiendome-a-la-nube-capitulo-uno.html
* Trying
* Connected to blog.grippo.com ( port 80 (#0)
> GET /blog/2009/07/subiendome-a-la-nube-capitulo-uno.html HTTP/1.1
> Host: blog.grippo.com
> User-Agent: curl/7.43.0
> Accept: */*
< HTTP/1.1 301 Moved Permanently
< Content-Length: 0
< Connection: keep-alive
< Date: Mon, 25 Jul 2016 19:33:47 GMT
< Location: http://blog.grippo.com/2009/07/03/subiendome_a_la_nube_capitulo_uno/index.html
< Server: AmazonS3
< X-Cache: Miss from cloudfront
< Via: 1.1 99c9f67869d77a26abed1c3a4b05cb92.cloudfront.net (CloudFront)
< X-Amz-Cf-Id: RLOsOGvdLEM6OdOzNkIqfsWG8-b3oGoivBK8Vg5vZuu6lPCyqrPUTw==
* Connection #0 to host blog.grippo.com left intact