Skip to content

Instantly share code, notes, and snippets.

@yorkxin
Last active October 27, 2020 12:17
Show Gist options
  • Select an option

  • Save yorkxin/5319661 to your computer and use it in GitHub Desktop.

Select an option

Save yorkxin/5319661 to your computer and use it in GitHub Desktop.
Amazon S3 Redirect Rules Generator

A Ruby script to generate simple Amazon S3 Redirection Rules.

Dependency

Nokogiri

Usage

ruby s3-routes-generator.rb input.txt

The generated XML is printed to STDOUT.

Sample Input

/home / /products/iphone /iphone /products /

Sample Output

home index.html products/iphone iphone products index.html

Assumptions

It assumes that:

  1. Website Hosting is enabled.
  2. Index Document is set to index.html.

License

None. I release this script to Public Domain.

require 'nokogiri'
routes = []
src = File.read(ARGV[0])
src.each_line do |line|
from, to = line.split(/\s+/)
from.gsub!(/\A\//, '')
to.gsub!(/\/\z/, '/index.html')
to.gsub!(/\A\//, '')
routes << { :from => from, :to => to }
end
builder = Nokogiri::XML::Builder.new do |xml|
xml.RoutingRules {
routes.each do |route|
xml.RoutingRule {
xml.Condition {
xml.KeyPrefixEquals route[:from]
}
xml.Redirect {
xml.ReplaceKeyWith route[:to]
}
}
end
}
end
puts builder.to_xml
@RameshJhajharia
Copy link

Is it possible to detect user agent from the request and redirect based on the user agent on amazon s3 static hosting?

@frob
Copy link

frob commented Jul 13, 2017

I am getting The XML you provided was not well-formed or did not validate against our published schema when I try to use this. It looks correct to me though.

@taqtiqa-mark
Copy link

taqtiqa-mark commented Jul 27, 2017

@frob the cause of the error message is the first line <?xml version="1.0"?>. Remove that and AWS accepts the XML. Having said that I am using handwritten XML but it looks the same to me - when I inserted the line I cited I saw that error message. HTH

@grantgeorge
Copy link

@RameshJhajharia I'm wondering the same thing. Did you ever arrive at an answer?

@andylshort
Copy link

@RameshJhajharia @grantgeorge WIth the standard advanced conditional redirect rules on an S3 bucket, you cannot detect a user agent, you can only act on the key of the request: https://docs.aws.amazon.com/AmazonS3/latest/dev/how-to-page-redirect.html#advanced-conditional-redirects

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment