Question

I want to write a Rack app that forwards requests to a different domain. The Faraday gem might work well for this. Something like this would be nice:

My config.ru file:

...
my_app = lambda do |env|
  conn = Faraday.new(env)
  conn.url = "http://some-other-domain.com"
  env.get? ? conn.get : conn.post
end

run my_app

Could it be this simple? Any ideas?

Was it helpful?

Solution

You might want to look at rack-rewrite (https://github.com/jtrupiano/rack-rewrite). You can use it to define and apply rewrite and redirect rules. A possible use of rack-rewrite that fits your use case is as follows:

require 'rack/rewrite'
use Rack::Rewrite do
  r301 %r{.*}, 'http://mynewdomain.com$&', :if => Proc.new {|rack_env|
    rack_env['SERVER_NAME'] != 'mynewdomain.com'
  }
end
# rest of your app

The signature of a rewrite rule is rewrite_method(request_url_expression, rewrite_url_expression, options). In this example, the method #r301 will provide a permanent redirect for all request urls matching the given regex to the new domain with the request URI (using the $& substitution operator). There're info more in the documentation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top