2

I've got a simple 301 redirect to capture all non .com domains I have registered for my site as follows:

DOMAIN = 'www.mywebsite.com'

use Rack::Rewrite do
  r301 %r{.*}, "http://#{DOMAIN}$&", :if => Proc.new {|rack_env|
    rack_env['SERVER_NAME'] != DOMAIN && ENV["RACK_ENV"] == 'production'
  }
end

I'd like to add a querystring to the response to add the original domain in the format

?utm_source=#{rack_env['SERVER_NAME']}

But can't quite work out how not to crash the server :) Can it be done & retain any original query string?

It's unlikely that anyone will hit any subpages under the main domain, but when I drop the $& from the rewrite, and replace it with my string, it blows up with no errors in the logs...

Les
  • 1,405
  • 15
  • 27

1 Answers1

2

I think the reason your original code won't work is because rack_env is not available within your second argument as it's a block argument to the third. Does that make sense?

You can however pass a Proc as the second argument of a redirect, so I think something like this should work (partially tested :)

DOMAIN = 'www.mywebsite.com'

ORIGINAL_REQUEST = Proc.new do |match, rack_env|
  "#{DOMAIN}?utm_source=#{rack_env['REQUEST_URI']}"
end

use Rack::Rewrite do
  r301 %r{.*}, ORIGINAL_REQUEST, :if => Proc.new {|rack_env|
    rack_env['SERVER_NAME'] != DOMAIN && ENV["RACK_ENV"] == 'production'
  }
end
jordelver
  • 8,292
  • 2
  • 32
  • 40