Ruby proxy setup for Net::HTTP, Faraday and HTTParty
Ruby proxy setup for Net::HTTP, Faraday 2 and HTTParty: proxy arguments, credentials, http_proxy and no_proxy, SOCKS5, 407 errors, reuse and rotation.

Quick summary · TL;DR
- Each client has one place for the proxy. Net::HTTP takes host, port, user and password as arguments 3-6 of new or start; Faraday 2 takes a proxy: URL or hash; HTTParty takes http_proxyaddr, http_proxyport, http_proxyuser and http_proxypass.
- HTTPS needs nothing extra. All three send a CONNECT request with Basic credentials to the proxy and run TLS to the website inside that tunnel.
- The environment rules differ. Net::HTTP and HTTParty read only http_proxy, even for https:// URLs, while Faraday reads https_proxy for them. Setting both variables to the same URL covers all three.
- A 407 changes shape with the scheme. It is a normal response on http:// URLs and an exception on https:// URLs: Net::HTTPClientException in Net::HTTP and HTTParty, Faraday::ConnectionFailed in Faraday.
A Ruby proxy setup comes down to one call per client. Net::HTTP takes the proxy host, port, username and password as arguments three to six of Net::HTTP.new or Net::HTTP.start. Faraday 2 takes a proxy: option, as a URL or a hash. HTTParty takes http_proxyaddr, http_proxyport, http_proxyuser and http_proxypass on a request, or http_proxy on a class. HTTPS URLs then go through a CONNECT tunnel on their own.
Trouble starts after that line. Net::HTTP ignores https_proxy even for HTTPS URLs, HTTParty quietly picks up http_proxy from the shell, Faraday reads a socks5:// URL as an HTTP proxy, and a 407 comes back as a response on one scheme and as an exception on the other. A rotating proxy can also return one IP for a whole run.
Each of those comes from how the three gems hand the request to Net::HTTP. Every snippet below was checked on Ruby 3.3 with net-http 0.10, Faraday 2.15 with faraday-net_http 3.5, HTTParty 0.24, open-uri 0.4, Mechanize 2.14 and socksify 1.8, against the gems’ own source (read October 17, 2026).
Ruby proxy setup by client
Keep the proxy details out of source control. Each example reads them from four environment variables, PROXY_HOST, PROXY_PORT, PROXY_USER and PROXY_PASS, so one Ruby proxy setup runs on a laptop, in CI and in production. Write the host as a bare name such as HOST, never http://HOST, in every argument form.
Net::HTTP proxy arguments
Ruby ships Net::HTTP in the standard library, so there is nothing to install. Its signature is Net::HTTP.new(address, port, p_addr, p_port, p_user, p_pass, p_no_proxy), and Net::HTTP.start takes the same positional arguments plus an options hash. This is the working minimum for a Ruby net http proxy:
require "net/http"
proxy_host = ENV.fetch("PROXY_HOST")
proxy_port = Integer(ENV.fetch("PROXY_PORT"))
proxy_user = ENV.fetch("PROXY_USER")
proxy_pass = ENV.fetch("PROXY_PASS")
uri = URI("https://httpbingo.org/ip")
Net::HTTP.start(uri.host, uri.port,
proxy_host, proxy_port, proxy_user, proxy_pass,
use_ssl: true, open_timeout: 10, read_timeout: 30) do |http|
res = http.get(uri.request_uri)
puts res.code, res.body
end
Default: the environment. Leave out the third argument and it becomes :ENV, so Net::HTTP looks for a proxy in the environment (covered below). Pass nil as the third argument to force a direct connection whatever the shell says.
HTTPS needs no extra flag. With use_ssl: true Net::HTTP opens a CONNECT HOST:443 request to the proxy, sends the credentials on it, waits for a 2xx, and starts TLS inside the tunnel. So the proxy sees the hostname and port, never the path or the headers. Ruby’s Net::HTTP documentation for 3.3 covers the proxy arguments in its Proxy Server section.
Bypass some hosts. An explicit proxy applies to every host, including the ones in no_proxy. Pass the seventh argument when a client also talks to internal services:
http = Net::HTTP.new("api.internal.example", 443,
proxy_host, proxy_port, proxy_user, proxy_pass,
"localhost,127.0.0.1,.internal.example")
http.proxy? # => false, this host goes direct
Entries with a leading dot cover every subdomain, and host:port limits an entry to one port. Older code builds a proxy class with Net::HTTP::Proxy(addr, port, user, pass) and calls .new on it. It still works, but the net-http source calls that class obsolete and points to the same arguments on Net::HTTP.new.
Faraday proxy option
Add gem "faraday" to the Gemfile; it pulls in the faraday-net_http adapter. For a Faraday proxy, the hash form is the safer default because it avoids any encoding question:
require "faraday"
conn = Faraday.new(
url: "https://httpbingo.org",
proxy: {
uri: "http://#{ENV.fetch('PROXY_HOST')}:#{ENV.fetch('PROXY_PORT')}",
user: ENV.fetch("PROXY_USER"),
password: ENV.fetch("PROXY_PASS")
},
request: { open_timeout: 10, timeout: 30 }
)
puts conn.get("/ip").body
URLs work too: proxy: "http://USERNAME:PASSWORD@HOST:PORT". It percent-decodes the user and password it finds there, so encode them first (see the authentication section). Both forms reach the same call: the adapter passes the proxy host, port, user and password to Net::HTTP.new, which is why everything in the Net::HTTP section also applies here.
Set a proxy per request
In Faraday 2 a proxy can also be set per request, not only when the connection is built. Faraday fills in the connection’s proxy first and runs the request block after, so a value set there wins:
require "faraday"
conn = Faraday.new(url: "https://httpbingo.org")
res = conn.get("/ip") do |req|
req.options.proxy = Faraday::ProxyOptions.from(
uri: "http://#{ENV.fetch('PROXY_HOST')}:#{ENV.fetch('PROXY_PORT')}",
user: ENV.fetch("PROXY_USER"),
password: ENV.fetch("PROXY_PASS")
)
end
Wrap the hash in Faraday::ProxyOptions.from. Passing a plain hash with a string uri sends it to the adapter unconverted, which fails with undefined method 'scheme'. To change the proxy for every later call, assign conn.proxy = "http://...". Accepted forms are listed in the Faraday ProxyOptions source.
HTTParty proxy options
An HTTParty proxy takes four request options. Here too the host is a bare name and the credentials are raw strings, so no encoding is needed:
require "httparty"
res = HTTParty.get("https://httpbingo.org/ip",
http_proxyaddr: ENV.fetch("PROXY_HOST"),
http_proxyport: Integer(ENV.fetch("PROXY_PORT")),
http_proxyuser: ENV.fetch("PROXY_USER"),
http_proxypass: ENV.fetch("PROXY_PASS"),
timeout: 30)
puts res.code, res.body
In an API wrapper class, set it once with the http_proxy class method, which takes the same four values in order:
require "httparty"
class IpEcho
include HTTParty
base_uri "https://httpbingo.org"
http_proxy ENV.fetch("PROXY_HOST"), Integer(ENV.fetch("PROXY_PORT")),
ENV.fetch("PROXY_USER"), ENV.fetch("PROXY_PASS")
default_timeout 30
end
puts IpEcho.get("/ip").body
Environment leaks in. HTTParty only passes proxy arguments to Net::HTTP when the http_proxyaddr key is present (connection_adapter.rb). Without it, Net::HTTP.new(host, port) runs with its :ENV default, so any http_proxy set in the shell or the container is used. Pass http_proxyaddr: nil on calls that must go direct.
open-uri and Mechanize proxies
Two more clients turn up in scraping scripts, and each handles credentials the opposite way to the other.
open-uri wants raw credentials. URI.open takes proxy_http_basic_authentication: with the proxy URL, the username and the password as plain strings:
require "open-uri"
proxy = "http://#{ENV.fetch('PROXY_HOST')}:#{ENV.fetch('PROXY_PORT')}"
URI.open("https://httpbingo.org/ip",
proxy_http_basic_authentication: [proxy, ENV.fetch("PROXY_USER"), ENV.fetch("PROXY_PASS")],
open_timeout: 10, read_timeout: 30) do |f|
puts f.read
end
Keep the login out of the URL here. When open-uri takes credentials from a proxy URL (its proxy: option, http_proxy or https_proxy), it splits them off without percent-decoding, so an encoded p%40ss reaches the proxy as p%40ss and earns a 407. Like Faraday, it reads https_proxy for https:// URLs, and proxy: nil switches the environment off. open-uri also raises OpenURI::HTTPError for a 407 on an http:// URL instead of returning a response.
Mechanize wants encoded credentials. agent.set_proxy(host, port, user, password) stores the login inside a URI, so a raw @, : or space raises URI::InvalidComponentError. Encode both parts; Mechanize decodes them before it sends the header:
require "mechanize"
agent = Mechanize.new
agent.set_proxy(ENV.fetch("PROXY_HOST"), Integer(ENV.fetch("PROXY_PORT")),
URI.encode_uri_component(ENV.fetch("PROXY_USER")),
URI.encode_uri_component(ENV.fetch("PROXY_PASS")))
agent.open_timeout = 10
agent.read_timeout = 30
puts agent.get("https://httpbingo.org/ip").body
Mechanize ignores http_proxy and https_proxy, so without set_proxy it always goes direct.
Environment variables and no_proxy
Exporting the proxy is the zero-code route, and it is where the three clients disagree most.
export http_proxy="http://USERNAME:PASSWORD@HOST:PORT"
export https_proxy="$http_proxy"
export no_proxy="localhost,127.0.0.1,.internal.example"
| Variable | Net::HTTP | Faraday 2 | HTTParty |
|---|---|---|---|
http_proxy for http:// URLs | used | used | used |
http_proxy for https:// URLs | used | not used | used |
https_proxy for https:// URLs | ignored | used | ignored |
no_proxy | honoured | honoured | honoured |
| Credentials in the URL | used, percent-decoded | used, percent-decoded | used, percent-decoded |
Only http_proxy counts for Net::HTTP. It looks up the environment with an http:// URI built from the target host, so the lookup reads http_proxy even when the request is HTTPS, and a shell with only https_proxy set sends Net::HTTP direct. By contrast, Faraday asks URI#find_proxy with the real scheme and does use https_proxy. Setting both variables to one URL, as above, keeps all three clients on the proxy.
Lowercase wins. Ruby’s URI#find_proxy reads http_proxy first and falls back to HTTP_PROXY with a warning. Under CGI, where any client can set HTTP_PROXY through a Proxy: header, the uppercase name is ignored. Loopback targets (127.x and ::1) never use the environment proxy.
The environment route also looks the target up locally. To spot loopback targets, URI#find_proxy resolves the target hostname on your own machine before the request goes to the proxy. That answer only decides whether the proxy is used at all (the loopback check, plus any IP ranges listed in no_proxy): the CONNECT request still carries the hostname, the proxy resolves it again, and the request exits where it should. What leaks is the name itself, because your own resolver sees every hostname the job visits, the client-side lookup that proxymint Lab #1 tests for. Both Net::HTTP and HTTParty do this whenever they fall back to http_proxy. In Faraday it happens when a connection is built while a matching proxy variable is set, even next to an explicit proxy: option, and again on each request to a full URL when the connection relies on the variables; Faraday.ignore_env_proxy = true stops both. To keep lookups off your machine, pass the proxy in code and leave the variables unset.
The get shortcuts follow it too. Both Net::HTTP.get and Net::HTTP.get_response call start with the :ENV default, so they use http_proxy like everything else. Old ruby-doc.org pages for Ruby 1.8 and 1.9, which still rank for this question, say Net::HTTP never reads the variable; on current Ruby the :ENV default does.
Ruby proxy authentication and 407s
All three clients send HTTP Basic credentials up front: as a Proxy-Authorization header on the CONNECT request for https:// URLs, and on the request itself for http:// URLs. There is no challenge round trip, so a 407 means the proxy rejected what it received. On every proxymint tier, proxy authentication is a username and password.
Encode credentials in URLs
Raw strings go in arguments, encoded strings in URLs. Net::HTTP arguments 5 and 6, HTTParty’s http_proxyuser and http_proxypass, and Faraday’s user: and password: keys take the password as it is. In a URL (Faraday’s string form, http_proxy) an @, : or space in the password breaks the parse, so encode both parts:
require "uri"
user = URI.encode_uri_component(ENV.fetch("PROXY_USER"))
pass = URI.encode_uri_component(ENV.fetch("PROXY_PASS"))
proxy_url = "http://#{user}:#{pass}@#{ENV.fetch('PROXY_HOST')}:#{ENV.fetch('PROXY_PORT')}"
URI.encode_uri_component (Ruby 3.2 and later) writes a space as %20, which both Faraday and Net::HTTP decode back. By contrast, URI.encode_www_form_component writes it as +, which Faraday keeps as a literal plus sign, so the password stops matching.
Keep the URL out of logs. Proxy URLs with credentials end up in exception messages, inspect output and error trackers, so log HOST:PORT only.
When a Ruby proxy fails
A 407 changes shape with the scheme. On an http:// URL the proxy’s 407 is the response, so the code gets a normal response object with code 407. On an https:// URL it answers the CONNECT before any response exists, and Net::HTTP raises.
| Symptom | Client | Cause | Fix |
|---|---|---|---|
res.code == "407" | all three, http:// URL | wrong or missing credentials | check arguments 5 and 6 or the encoded URL |
Net::HTTPClientException: 407 "Proxy Authentication Required" | Net::HTTP and HTTParty, https:// URL | CONNECT refused | same; e.response.code holds "407" |
Faraday::ConnectionFailed with message 407 ... | Faraday, https:// URL | CONNECT refused | same; a status check alone never sees it |
wrong status line | Faraday | socks5:// scheme | use socks:// and socksify |
407 although the password is right | open-uri | encoded login in a proxy URL, sent undecoded | use proxy_http_basic_authentication with raw values |
URI::InvalidComponentError | Mechanize | raw @, : or space in set_proxy | encode user and password |
Net::OpenTimeout (Faraday::ConnectionFailed in Faraday) | all three | proxy host or port unreachable | check the port, then raise open_timeout |
| request goes direct, no error | Net::HTTP, HTTParty | only https_proxy set, or a no_proxy match | set http_proxy or pass the proxy explicitly |
Rescue both shapes in one place:
begin
res = http.request(Net::HTTP::Get.new(uri))
raise "proxy rejected the credentials" if res.code == "407"
rescue Net::HTTPClientException => e
raise "proxy rejected the credentials" if e.response.code == "407"
raise
rescue Net::OpenTimeout, Net::ReadTimeout => e
warn "proxy timed out: #{e.class}"
raise
end
Set open_timeout and read_timeout every time. By default Net::HTTP waits 60 seconds for both, so a dead proxy port can hold a worker for a minute per call. The 407 Proxy Authentication Required guide lists the causes by client.
Ruby SOCKS5 proxy setup
Net::HTTP has no SOCKS support. The socksify gem adds a Net::HTTP.socks_proxy class method that returns a Net::HTTP subclass routed over SOCKS5 with username and password authentication:
require "socksify/http"
socks_http = Net::HTTP.socks_proxy(ENV.fetch("PROXY_HOST"),
Integer(ENV.fetch("PROXY_PORT")),
username: ENV.fetch("PROXY_USER"),
password: ENV.fetch("PROXY_PASS"))
socks_http.start("httpbingo.org", 443, use_ssl: true) do |http|
puts http.get("/ip").body
end
socksify sends the target as a hostname in the SOCKS5 request, so DNS resolves on the proxy side, which is what socks5h:// means in curl. Use the class socks_proxy returns rather than calling TCPSocket.socks_server=, which routes every socket in the process.
For a Ruby SOCKS5 proxy, Faraday needs the socks:// scheme and socksify in the Gemfile: proxy: "socks://USERNAME:PASSWORD@HOST:PORT". Its net_http adapter checks for exactly that scheme.
HTTParty has no SOCKS option, so point it at the HTTP endpoint. Every proxymint tier includes HTTP as well as SOCKS5. Over HTTP the hostname travels to the proxy in the CONNECT request, so names still resolve on the proxy side, and passing http_proxyaddr in code skips the local lookup of the environment route. When SOCKS is worth the extra gem is covered in SOCKS5 vs HTTP proxy.
Connection reuse and rotation
Rotation on a gateway happens on the proxy side. On a proxymint order it is a setting: a new IP on every request, a timer from 5 to 60 minutes, or sticky for as long as the IP stays online, and it can be changed later with the same login. Session parameters in the username do not apply. For an https:// target, each CONNECT tunnel is one TCP connection through one exit, so what Ruby controls is how many tunnels it opens.
One start block, one tunnel. Every request inside a Net::HTTP.start block reuses one keep-alive connection, so it rides one CONNECT tunnel and leaves from one exit. That suits a login flow on a sticky setting.
Faraday and HTTParty reconnect each call. Both the faraday-net_http adapter and HTTParty build a fresh Net::HTTP object per request, so each call opens its own connection and its own tunnel. That suits every-request rotation. Mechanize keeps connections open between requests through net-http-persistent, so it behaves like one start block.
To see what your setup does, count exits both ways:
require "net/http"
require "json"
args = [ENV.fetch("PROXY_HOST"), Integer(ENV.fetch("PROXY_PORT")),
ENV.fetch("PROXY_USER"), ENV.fetch("PROXY_PASS")]
reused = Net::HTTP.start("httpbingo.org", 443, *args, use_ssl: true) do |http|
5.times.map { JSON.parse(http.get("/ip").body)["origin"] }
end
fresh = 5.times.map do
Net::HTTP.start("httpbingo.org", 443, *args, use_ssl: true) do |http|
JSON.parse(http.get("/ip").body)["origin"]
end
end
puts "one connection: #{reused.uniq.size} exits"
puts "new connections: #{fresh.uniq.size} exits"
For a list of static endpoints, rotate in Ruby instead: keep the proxy URLs in an array and pass proxies[i % proxies.size] to Faraday.new or to Net::HTTP.start per job. Which mode breaks which kind of job is covered in rotating vs sticky proxies.
Choose a Ruby proxy setup
Check the exit once before a job runs. Call an https:// IP echo endpoint through the client and once without it, and compare the two addresses. Use https:// for that check: in the proxymint Lab #1 measurement (September 28, 2026) the gateway answered plain http:// requests with a 301 to the https:// address, which a naive health check reads as a failure. That run also found no Via or Forwarded header added to requests, so the target sees only what your Ruby code sends.
Then pick the proxy type by target:
- Pages that show home users different content, such as prices, stock or local search, need rotating residential proxies; pair them with Faraday or HTTParty and every-request rotation.
- A session that holds a cookie or a login for days fits static ISP proxies and a single Net::HTTP connection.
- If the target is an API or a site that accepts hosting networks, datacenter proxies carry volume with the same code.
- If the shell already exports a corporate proxy, pass
nil(Net::HTTP) orhttp_proxyaddr: nil(HTTParty) on calls that must not use it.
Where those residential exits come from is explained in what is a residential proxy. Whatever the type, a Ruby proxy setup stays the same four values: host, port, username and password.
Frequently asked questions
Pass the proxy to the HTTP client you already use. Net::HTTP takes the proxy host, port, username and password as arguments three to six of Net::HTTP.new or Net::HTTP.start, Faraday takes a proxy: option on Faraday.new, and HTTParty takes http_proxyaddr, http_proxyport, http_proxyuser and http_proxypass. open-uri takes proxy_http_basic_authentication with raw credentials, and Mechanize takes agent.set_proxy with percent-encoded ones. Exporting http_proxy and https_proxy in the shell also works without code changes.
Call Net::HTTP.new(host, port, proxy_host, proxy_port, proxy_user, proxy_pass), or pass the same values to Net::HTTP.start. The proxy host is a bare name without http://, and the username and password are raw strings that need no encoding. Net::HTTP sends them as a Basic Proxy-Authorization header, on the CONNECT request for https:// URLs.
Yes, when the third argument is left out, because it defaults to :ENV. Net::HTTP reads http_proxy (or HTTP_PROXY, with a warning) for both http:// and https:// URLs, honours no_proxy, and uses percent-decoded credentials from the URL. It ignores https_proxy, so a shell that sets only https_proxy sends Net::HTTP direct.
Pass proxy: to Faraday.new, either as a URL like http://USERNAME:PASSWORD@HOST:PORT with the credentials percent-encoded, or as a hash with uri, user and password keys. In Faraday 2 a single request can override it by setting req.options.proxy to Faraday::ProxyOptions.from(...) in the request block. Without the option, Faraday reads http_proxy, https_proxy and no_proxy unless Faraday.ignore_env_proxy is true.
Pass http_proxyaddr, http_proxyport, http_proxyuser and http_proxypass to HTTParty.get or any other request method, or call http_proxy with the same four values inside a class that includes HTTParty. The address is a bare host name. Without http_proxyaddr, HTTParty falls back to Net::HTTP's environment lookup, so pass http_proxyaddr: nil for calls that must go direct.
Not with Net::HTTP alone. The socksify gem adds Net::HTTP.socks_proxy(host, port, username:, password:), which returns a Net::HTTP subclass routed over SOCKS5 and sends the hostname to the proxy for DNS. Faraday uses socksify when the proxy URL starts with socks://, and HTTParty has no SOCKS option.
The proxy did not accept the credentials it received. Common causes are a password with @, : or a space that was not percent-encoded in a proxy URL, credentials left out of the Net::HTTP arguments, or a wrong or expired login. On http:// URLs the 407 arrives as a response; on https:// URLs Net::HTTP and HTTParty raise Net::HTTPClientException and Faraday raises Faraday::ConnectionFailed.
Researched and drafted with AI tools, then checked against our publishing rules before it went live: 6 outside links, 8 links to other proxymint pages, no prices and a fact-check pass against our product records. How we write.
