diff --git a/lib/rack/url.rb b/lib/rack/url.rb index 3e9767a..98a24d2 100644 --- a/lib/rack/url.rb +++ b/lib/rack/url.rb @@ -6,14 +6,25 @@ module Rewritten class Url + attr_accessor :base_url + def initialize(app, &block) @app = app @translate_backwards = false @downcase_before_lookup = false @translate_partial = false + @base_url = '' instance_eval(&block) if block_given? end + def is_internal_target?(url) + url.nil? or url.start_with?('/') or url.start_with?(@base_url) + end + + def is_external_target?(url) + !is_internal_target?(url) + end + def call(env) req = Rack::Request.new(env) @@ -22,7 +33,13 @@ def call(env) path = "#{subdomain}#{req.path_info}" path.downcase! if downcase_before_lookup? - if ::Rewritten.includes?(path.chomp("/")) or backwards=( translate_backwards? && ::Rewritten.exist_translation_for?(path) ) + target_url = ::Rewritten.translate(path) + + if is_external_target?(target_url) + r = Rack::Response.new + r.redirect(target_url, 301) + r.finish + elsif ::Rewritten.includes?(path.chomp("/")) or backwards=( translate_backwards? && ::Rewritten.exist_translation_for?(path) ) to = ::Rewritten.includes?(path.chomp("/")) || path diff --git a/test/rack/rewritten_url_test.rb b/test/rack/rewritten_url_test.rb index babcbf4..c04f14e 100644 --- a/test/rack/rewritten_url_test.rb +++ b/test/rack/rewritten_url_test.rb @@ -61,6 +61,26 @@ def request_url(url, params={}) ret[0].must_equal 200 end + describe 'external redirection' do + + before { + @app = MiniTest::Mock.new + @rack = Rack::Rewritten::Url.new(@app) do |config| + config.base_url = 'http://www.example.org' + end + + Rewritten.add_translation '/external/target', 'http://www.external.com' + } + + it "must redirect to external target" do + ret = @rack.call request_url('/external/target') + @app.verify + ret[0].must_equal 301 + ret[1]['Location'].must_equal "http://www.external.com" + end + + end + describe "partial translation" do before do