HTTP Proxy in Rails

Sometimes you want to hide a backend system behind a frontend Rails app without using nginx and likes. I’ll leave a discussion why it’s a bad idea until the next time.

Today I’m going to show you how you can use a Rack lib to do just that.

First of all, add this line to your Gemfile:

gem 'rack-proxy'

Then run your bundle:

bundle install

At this point you have the gem installed. Now you have to create a Rack worker, which you’ll mount in your routes.rb file later.

Go to lib/ and create rails_proxy.rb:

class RailsProxy < Rack::Proxy
  def rewrite_env(env)
    env['HTTP_HOST'] = ''
    env['SERVER_PORT'] = 80

    # Remove forwarding parameters
    env['SCRIPT_NAME'] = nil
    env['HTTP_X_FORWARDED_PORT'] = nil
    env['HTTP_X_FORWARDED_PROTO'] = nil

    # Do some other stuff as needed
    # ...

    # Return the 'env'

Now let’s mount our new proxy! In your routes.rb add these lines:

mount => '/rails/proxy'

That’s it! Now if we go to http://localhost:3000/rails/proxy/test, our request will be redirected to Pretty neat, eh? :)