diff --git a/README.md b/README.md index 1092320..a52cad4 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,19 @@ your domains. The configuration is kept public on this github repository itself. To add a DNS record, point your domain via a CNAME entry to `lightsaber.captnemo.in`. +You can also have fallthrough domain redirects +(thanks to @vivekprakash for the suggestion), by making the redirect a hash +with a `root` key set to the url prefix. + +```yaml +# This is a fallthrough redirect +# so t.co/ev would redirect to twitter.com/ev +t.co: + root: https://twitter.com +# All goo.gl routes will forward to google.com, and not use fallthrough +goo.gl: https://google.com +``` + Next, you will need to do the following: 1. Fork this repo diff --git a/app.rb b/app.rb index f5966cd..604924b 100644 --- a/app.rb +++ b/app.rb @@ -3,11 +3,26 @@ require 'bundler/setup' require 'sinatra' require 'yaml' -get '/' do +def get_url(domain_object, rel_route) + if domain_object.is_a? Hash + return domain_object['root'] + rel_route + elsif domain_object.is_a? String + return domain_object + end +end + +get '/*' do hostname = request.host + route = params[:splat][0] + YAML::load_file('redirects.yml').each do |code, zone| if zone.has_key? hostname - redirect zone[hostname], code + url = get_url(zone[hostname], route) + if url + redirect url, code + else + halt 400, "Invalid configuration for #{hostname}" + end end end diff --git a/redirects.yml b/redirects.yml index e774c83..99fba8b 100644 --- a/redirects.yml +++ b/redirects.yml @@ -1,6 +1,9 @@ --- 301: - github.captnemo.in: https://github.com/captn3m0 + # This is the base root for all requests + # github.captnemo.in/lightsaber => github.com/captn3m0/lightsaber + github.captnemo.in: + root: https://github.com/captn3m0 lightsaber.captnemo.in: https://github.com/captn3m0/lightsaber 302: fb.captnemo.in: https://facebook.com/captn3m0 \ No newline at end of file diff --git a/test.rb b/test.rb index 22474a8..73a2b48 100644 --- a/test.rb +++ b/test.rb @@ -18,6 +18,8 @@ class TestConfig < Minitest::Test def test_each_domain @config.each do |section, zone| zone.each do |domain, redirect| + url = get_url(redirect, "") + refute_nil url, "Invalid YAML config for #{domain}" assert resolves_to_lightsaber(domain), "DNS for #{domain} isn't setup yet. See README" end @@ -34,4 +36,12 @@ class TestConfig < Minitest::Test end flag end + + def get_url(domain_object, rel_route) + if domain_object.is_a? Hash + return domain_object['root'] + rel_route + elsif domain_object.is_a? String + return domain_object + end + end end \ No newline at end of file