rack-rewrite icon indicating copy to clipboard operation
rack-rewrite copied to clipboard

Adding a custom querystring to response

Open oldtinroof opened this issue 12 years ago • 1 comments

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 requested domain in the format so that I can track what domains people are hitting.

?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...

*nb: I asked this on SO a week ago with no replies, so I thought I'd post here.

oldtinroof avatar Jan 25 '13 10:01 oldtinroof

Ok, this is ugly but it's the best I could come up with for my situation, which is similar:

r301 %r{.*(\?.*)?}, lambda { |match, rack_env|
      "/to?utm_source=whatevers#{match[1]}".gsub("utm_source=whatevers?", "utm_source=whatevers&")
}

swrobel avatar Apr 25 '13 21:04 swrobel