Building a simple forward proxy in Ruby with WEBRick requires very little code. Here is a small sample that forwards all requests but for the example.com domain, which it blocks.

require 'webrick/httpproxy'

def handle_request(req, res)
  puts "[REQUEST] " + req.request_line
  if req.host == "example.com" || req.host == "www.example.com"
    res.header['content-type'] = 'text/html'
    res.header.delete('content-encoding')
    res.body = "Access is denied."
  end
end

if $0 == __FILE__ then
  server = WEBrick::HTTPProxyServer.new(
    :Port => 8123,
    :AccessLog => [],
    :ProxyContentHandler => method(:handle_request))
  trap "INT" do server.shutdown end
  server.start
end

The interesting bit is the handle_request method. WEBRick provides us with the request and response instance for each request, so that we can check what’s being requested and block certain URLs. Since the response is also already available, we can even perform content filtering.