Your Rust service already calls an API with reqwest, and now that traffic has to leave through a proxy. Maybe a partner allowlists one fixed IP, a test needs an exit in another country, or the company network only lets traffic out through its own proxy. reqwest handles this with one builder call, but the defaults can surprise you: environment variables apply before you write any proxy code, your own proxy switches them off, SOCKS5 is a Cargo feature, and a pooled connection keeps its exit IP.
This guide covers Proxy::all, http and https, credentials, SOCKS5 and socks5h, the HTTP_PROXY / HTTPS_PROXY / NO_PROXY rules, the blocking client, timeouts, TLS, rotation, a complete exit-IP checker with retries, and the usual errors. The API matches reqwest 0.13.5, the current release on crates.io in November 2026. Rust was not installed on our test machine, so the code follows the official documentation and the crate's source line by line, and the post shows no program output. If you want to try the gateway from a shell first, the same endpoint works in cURL with a proxy.
How does reqwest decide which proxy a request uses?
A reqwest Client holds a list of proxy rules, and every new connection walks that list in the order the rules were added. The first rule that matches the target decides where the connection goes. If you never call .proxy() on the builder, the list holds one "system" rule built from environment variables and, with the default system-proxy feature, the Windows or macOS proxy settings.
What happens next depends on the target and the proxy type:
- The client picks a rule.
Proxy::httpmatches onlyhttp://targets,Proxy::httpsonlyhttps://targets,Proxy::allboth, andProxy::customwhatever your closure returns. ANoProxylist attached to the rule can exclude hosts. - It connects to the proxy, not the target. A SOCKS URL without a port gets 1080.
- Plain
http://target through an HTTP proxy. The request goes to the proxy with the full URL in the request line and theProxy-Authorizationheader. https://target through an HTTP proxy. reqwest sendsCONNECT host:443with the credentials, and after the proxy answers200the TLS handshake runs inside that tunnel. The proxy sees only the host and port. The CONNECT method is defined in RFC 9110.- SOCKS5 proxy. reqwest runs the SOCKS handshake, logs in if the URL has credentials, and asks the proxy to connect. With
socks5h://it sends the host name; withsocks5://it resolves the name itself first. - The connection is pooled. The next request to the same host reuses it, so no new rule lookup and no new tunnel happen until that connection closes.
Which Cargo features do you need?
The default features are enough for HTTP and HTTPS proxies; SOCKS5, the blocking client and JSON decoding are opt-in. The reqwest crate documentation lists http2, default-tls, charset and system-proxy as the defaults, and socks, blocking and json as optional.
[dependencies]
# socks: SOCKS5 proxies, json: Response::json(); add "blocking" for the synchronous client
reqwest = { version = "0.13", features = ["json", "socks"] }
tokio = { version = "1", features = ["full"] }Two 0.13 changes matter when you copy older examples. rustls is now the default TLS backend, and the old rustls-tls feature is now called rustls. The query and form features are no longer on by default, so .query() and .form() need them listed.
How do you set a proxy with reqwest::Proxy?
Create a Proxy, hand it to ClientBuilder::proxy, and build the client once. Keep that client for the life of the program: it owns the connection pool, and cloning it is cheap.
use std::collections::HashMap;
use std::time::Duration;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// One proxy for both http:// and https:// targets. The panel's Endpoint Generator prints this address.
let proxy = reqwest::Proxy::all("http://user:pass@pr.proxynet.io:8000")?;
let client = reqwest::Client::builder()
.proxy(proxy)
.connect_timeout(Duration::from_secs(10)) // reaching the proxy
.timeout(Duration::from_secs(30)) // the whole request, body included
.build()?;
let body: HashMap<String, String> = client
.get("https://api.ipify.org?format=json")
.send()
.await?
.error_for_status()?
.json()
.await?;
println!("exit IP: {}", body["ip"]);
Ok(())
}The scheme in the proxy URL is the proxy's type, not the target's. http:// means a plain HTTP proxy, which is what most gateways run on their HTTP port, even when every target is https://. Write https:// only when the provider says the port speaks TLS.
If you need different proxies for the two kinds of target, add two rules. The Proxy documentation is explicit that Proxy::http leaves https:// URLs alone, a common reason a client "ignores" its proxy:
let client = reqwest::Client::builder()
.proxy(reqwest::Proxy::http("http://user:pass@pr.proxynet.io:8000")?) // http:// targets
.proxy(reqwest::Proxy::https("http://user:pass@pr.proxynet.io:8000")?) // https:// targets
.build()?;Rule order matters: reqwest checks rules in the order you added them, so a Proxy::all placed first catches everything and the rules after it never match.
How do you pass the proxy username and password?
Put them in the proxy URL or call .basic_auth() on the Proxy; both end up as a Proxy-Authorization: Basic … header for HTTP proxies and as the username/password login for SOCKS5. reqwest percent-decodes the user and password it finds in the URL, so special characters must be encoded there.
// Credentials in the URL: encode @ : / # and other reserved characters
// "p@ss:word" becomes "p%40ss%3Aword"
let in_url = reqwest::Proxy::all("http://user:p%40ss%3Aword@pr.proxynet.io:8000")?;
// Or keep the URL clean and pass the raw values
let with_method = reqwest::Proxy::all("http://pr.proxynet.io:8000")?
.basic_auth("user", "p@ss:word");.basic_auth() takes the password as it is, the safer choice when it comes from a secret store. A gateway can also authenticate by IP whitelist, which leaves no password in the URL and suits a server with a fixed address.
How do you use a SOCKS5 proxy with reqwest?
Enable the socks feature and use a socks5h:// or socks5:// URL in the same Proxy::all call. The SOCKS5 handshake, including the username/password login from RFC 1928 and its companion RFC 1929, runs inside reqwest.
// Cargo.toml: reqwest = { version = "0.13", features = ["socks"] }
// socks5h: the proxy resolves the host name, so no DNS query leaves your network
let proxy = reqwest::Proxy::all("socks5h://user:pass@pr.proxynet.io:1080")?;
let client = reqwest::Client::builder()
.proxy(proxy)
.timeout(std::time::Duration::from_secs(30))
.build()?;The letter h decides who resolves DNS. reqwest's connector maps socks5 and socks4 to local resolution and socks5h and socks4a to resolution at the proxy:
| Scheme | Who resolves the host name | Use it when |
|---|---|---|
socks5h:// | The proxy | The exit's location should match DNS |
socks5:// | Your machine | The target is only in your local DNS |
socks4a:// | The proxy | An old proxy speaks SOCKS4 only |
socks4:// | Your machine | Legacy setups; no username/password |
With socks5://, your own DNS server sees every host you visit and geo-aware DNS answers for your location rather than the exit's. For most proxy work socks5h:// is the right default. The protocol itself is explained in What Is a SOCKS5 Proxy?.
Without the socks feature the URL still parses, but reqwest treats the address as an HTTP proxy and the request fails while connecting, with no message about the missing feature. Proxynet's SOCKS5 Proxy runs on its own port next to the HTTP port, with the same username and password.
How does reqwest read HTTP_PROXY, HTTPS_PROXY and NO_PROXY?
reqwest reads the proxy environment variables automatically, but only while you have not called .proxy() or .no_proxy() on the builder. reqwest::get and Client::new() therefore honour them out of the box. The rules, from the documentation and the hyper-util matcher that reqwest 0.13 uses:
HTTP_PROXYapplies tohttp://targets andHTTPS_PROXYtohttps://targets.ALL_PROXYcovers both, and the two specific variables win over it.- Each variable is checked in uppercase first, then lowercase (
HTTP_PROXY, thenhttp_proxy). NO_PROXYis a comma-separated list of domains, IPv4 or IPv6 addresses and CIDR ranges such as10.0.0.0/8. A domain matches itself and all subdomains, a dot in front of it changes nothing, and*alone turns proxying off.- A value with a scheme other than
http,https,socks4,socks4a,socks5orsocks5his skipped, not reported. - When
REQUEST_METHODis set, as in a CGI script, the environment proxies are ignored as a protection against header injection. - With the default
system-proxyfeature, reqwest also reads the Windows and macOS proxy settings when the variables are empty.
There is no built-in exception for localhost, unlike some other HTTP clients. If a local service must stay direct, list localhost and 127.0.0.1 in NO_PROXY.
The same exclusion list works on a proxy you set in code:
use reqwest::{NoProxy, Proxy};
let proxy = Proxy::all("http://user:pass@pr.proxynet.io:8000")?
// internal hosts and the local machine go direct
.no_proxy(NoProxy::from_string("localhost, 127.0.0.1, .internal.example.com, 10.0.0.0/8"));
// Or reuse whatever NO_PROXY / no_proxy says
let proxy_from_env = Proxy::all("http://user:pass@pr.proxynet.io:8000")?.no_proxy(NoProxy::from_env());ClientBuilder::no_proxy() is a different thing: it clears every proxy and the environment lookup, which is what you want for a client that must never use one, for example a health check against your own network.
Which proxy method fits which situation?
| Method | Scope | Covers | Note |
|---|---|---|---|
| Environment variables | Every default client | Set per scheme | Off once .proxy() is called |
Proxy::all(url) | That client | http:// and https:// | The usual choice |
Proxy::http + Proxy::https | That client | One scheme each | Two rules, order matters |
Proxy::custom(closure) | That client | Your decision per target | Per-host routing, small pools |
ClientBuilder::no_proxy() | That client | Nothing | Also disables the environment |
How do you use the blocking client with a proxy?
The blocking client takes the same Proxy values; only the types change. Enable the blocking feature, build reqwest::blocking::Client, and drop the .awaits.
// Cargo.toml: reqwest = { version = "0.13", features = ["blocking", "json"] }
use std::collections::HashMap;
use std::time::Duration;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = reqwest::blocking::Client::builder()
.proxy(reqwest::Proxy::all("http://user:pass@pr.proxynet.io:8000")?)
.timeout(Duration::from_secs(30))
.build()?;
let body: HashMap<String, String> = client
.get("https://api.ipify.org?format=json")
.send()?
.error_for_status()?
.json()?;
println!("exit IP: {}", body["ip"]);
Ok(())
}Two differences from the async client. The blocking client has a default timeout of 30 seconds, while the async client has none until you set one. And building a blocking client inside a Tokio runtime panics, so a program that already has #[tokio::main] should use the async client throughout.
How do rotation and sticky sessions work with reqwest?
A rotating gateway picks the exit IP when a connection is opened, so with reqwest the exit changes only when the pool opens a new connection. By default the client keeps idle connections and, for HTTPS targets, may multiplex many requests over one HTTP/2 connection. Ten quick requests to the same API can therefore leave through one exit.
For a new exit on every request, stop the pool from keeping connections and stay on HTTP/1.1:
let client = reqwest::Client::builder()
.proxy(reqwest::Proxy::all("http://user:pass@pr.proxynet.io:8000")?)
.pool_max_idle_per_host(0) // close each connection after use: a new tunnel per request
.http1_only() // no HTTP/2 multiplexing over one tunnel
.timeout(std::time::Duration::from_secs(30))
.build()?;The opposite case, a login flow that must keep one IP, needs the default pool plus a session parameter in the proxy username. The panel's Endpoint Generator builds that username for the country, city and session you choose; a Residential Proxy gateway rotates the exit for each new tunnel through one address, and a sticky session holds one exit for 1 to 60 minutes.
If you have your own list of proxy addresses, Proxy::custom can hand them out in turn. The closure runs when the client needs a new connection, so the pooling rule above still applies:
use std::sync::atomic::{AtomicUsize, Ordering};
let proxies = vec![
"http://user:pass@pr.proxynet.io:8000".to_string(),
"http://user:pass@pr.proxynet.io:8001".to_string(),
];
let next = AtomicUsize::new(0);
// Round-robin over the list; return None to send a target direct
let proxy = reqwest::Proxy::custom(move |_url| {
let i = next.fetch_add(1, Ordering::Relaxed) % proxies.len();
Some(proxies[i].clone())
});Timeouts and TLS
Set timeout on every async client, or an exit that stops answering keeps a task waiting forever. timeout covers the whole request, connect_timeout the connection to the proxy, and read_timeout each read, resetting after every successful one, which suits large downloads. RequestBuilder::timeout overrides the client value for one request.
TLS needs one rule: never turn certificate checks off to make a proxy work. In 0.13 the default rustls backend uses the operating system's trust store through rustls-platform-verifier, so a company CA installed on the machine is usually already trusted. If a corporate proxy inspects TLS with its own CA that the system does not know, add that certificate with tls_certs_merge:
// The corporate proxy's CA certificate, in PEM format
let pem = std::fs::read("corp-ca.pem")?;
let ca = reqwest::tls::Certificate::from_pem(&pem)?;
let client = reqwest::Client::builder()
.proxy(reqwest::Proxy::all("http://proxy.corp.example:3128")?)
.tls_certs_merge([ca]) // add to the built-in roots instead of replacing them
.build()?;tls_danger_accept_invalid_certs(true), the 0.13 name of the old danger_accept_invalid_certs, is only a diagnostic: if a request works with it, the problem is a certificate, and the fix is the right CA. A provider's gateway does not touch the TLS inside the tunnel.
A complete example: exit-IP check with retries and a concurrency cap
The program below combines the pieces: a client with a proxy and timeouts, eight checks against an IP-echo service, at most four at a time, retries with exponential backoff and jitter for network errors, 429 and 5xx, a server's Retry-After honoured, and no retry on a 407.
// main.rs - check the exit IP through a proxy: timeouts, retries with backoff, at most 4 requests at once.
// Cargo.toml: reqwest = { version = "0.13", features = ["json"] }, tokio = { version = "1", features = ["full"] }
use std::collections::HashMap;
use std::error::Error;
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use reqwest::header::RETRY_AFTER;
use reqwest::{Client, Proxy, StatusCode};
use tokio::sync::Semaphore;
use tokio::task::JoinSet;
const MAX_ATTEMPTS: u32 = 4; // first try + 3 retries
const MAX_IN_FLIGHT: usize = 4; // requests running at the same time
const ECHO_URL: &str = "https://api.ipify.org?format=json";
fn build_client(proxy_url: &str) -> Result<Client, reqwest::Error> {
Client::builder()
.proxy(Proxy::all(proxy_url)?)
.connect_timeout(Duration::from_secs(10)) // reaching the proxy
.timeout(Duration::from_secs(30)) // the whole request
.user_agent("exit-ip-check/1.0")
.build()
}
// 1, 2, 4 s ... capped at 30 s, plus up to 1 s of jitter so tasks do not retry in lockstep.
fn backoff(attempt: u32) -> Duration {
let base = Duration::from_secs((1u64 << (attempt - 1)).min(30));
let jitter_ms = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.subsec_millis())
.unwrap_or(0);
base + Duration::from_millis(u64::from(jitter_ms))
}
// For an https:// target the proxy's 407 arrives while the tunnel is being opened,
// so reqwest returns an error, not a response. Look for it in the error chain.
fn is_proxy_auth_error(err: &reqwest::Error) -> bool {
let mut source = err.source();
while let Some(inner) = source {
if inner.to_string().contains("proxy authorization required") {
return true;
}
source = inner.source();
}
false
}
// One check. Network errors, timeouts, 429 and 5xx are retried; a 407 is not,
// because the credentials are wrong and another attempt would send the same ones.
async fn exit_ip(client: &Client) -> Result<String, String> {
let mut last_error = String::new();
for attempt in 1..=MAX_ATTEMPTS {
let mut wait = backoff(attempt);
match client.get(ECHO_URL).send().await {
Ok(resp) if resp.status().is_success() => {
let body: HashMap<String, String> = resp.json().await.map_err(|e| e.to_string())?;
return body.get("ip").cloned().ok_or_else(|| "no \"ip\" field".to_string());
}
Ok(resp) if resp.status() == StatusCode::PROXY_AUTHENTICATION_REQUIRED => {
// plain http:// target: the 407 is an ordinary response
return Err("407: check user:pass or the IP whitelist".to_string());
}
Ok(resp) if resp.status() == StatusCode::TOO_MANY_REQUESTS || resp.status().is_server_error() => {
// The server asked us to slow down: its Retry-After (in seconds) wins over our schedule.
if let Some(secs) = resp
.headers()
.get(RETRY_AFTER)
.and_then(|v| v.to_str().ok())
.and_then(|s| s.parse::<u64>().ok())
{
wait = Duration::from_secs(secs);
}
last_error = format!("HTTP {}", resp.status());
}
Ok(resp) => return Err(format!("HTTP {}", resp.status())), // 403, 404 ... not retried
Err(e) if is_proxy_auth_error(&e) => {
return Err("407 on CONNECT: check user:pass or the IP whitelist".to_string());
}
Err(e) if e.is_connect() || e.is_timeout() => last_error = format!("{e:?}"),
Err(e) => return Err(format!("{e:?}")),
}
if attempt < MAX_ATTEMPTS {
eprintln!("attempt {attempt}/{MAX_ATTEMPTS}: {last_error}, waiting {wait:?}");
tokio::time::sleep(wait).await;
}
}
Err(last_error)
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
// Keep the real address in an environment variable, not in git.
let proxy_url = std::env::var("PROXY_URL")
.unwrap_or_else(|_| "http://user:pass@pr.proxynet.io:8000".to_string());
let client = build_client(&proxy_url)?;
let limit = Arc::new(Semaphore::new(MAX_IN_FLIGHT));
let mut tasks = JoinSet::new();
for n in 1..=8 {
let client = client.clone(); // cheap: the clones share one connection pool
let limit = Arc::clone(&limit);
tasks.spawn(async move {
let _permit = limit.acquire_owned().await.expect("semaphore closed");
(n, exit_ip(&client).await)
});
}
while let Some(joined) = tasks.join_next().await {
match joined? {
(n, Ok(ip)) => println!("check {n}: exit IP {ip}"),
(n, Err(e)) => println!("check {n}: failed: {e}"),
}
}
Ok(())
}Three design points. A 407 for a plain http:// target is an ordinary response, but for an https:// target the proxy refuses the CONNECT and reqwest returns a connection error whose cause chain contains proxy authorization required (hyper-util's tunnel text in the 0.13.5 source); there is no typed error, so the program searches the chain. A 403 or 404 is returned at once, because another attempt does not change what the page is. And the eight checks share one pool, so through a rotating gateway several may report the same exit; add pool_max_idle_per_host(0) and http1_only() when each check needs its own tunnel.
How do you check that requests really go through the proxy?
Ask an IP-echo service which address it sees, once with a client that never uses a proxy and once with yours. The direct client needs ClientBuilder::no_proxy(); Client::new() would quietly pick up HTTPS_PROXY from the environment and spoil the comparison.
let direct = reqwest::Client::builder().no_proxy().build()?;
let proxied = reqwest::Client::builder()
.proxy(reqwest::Proxy::all("http://user:pass@pr.proxynet.io:8000")?)
.build()?;
for (label, client) in [("without proxy", &direct), ("with proxy", &proxied)] {
let ip = client.get("https://api.ipify.org").send().await?.text().await?;
println!("{label}: {ip}");
}Two different addresses, the second in the country you asked for, mean the proxy works. Two identical lines usually mean a Proxy::http rule with an https:// target, a host caught by a NoProxy list, or a proxy URL with a scheme reqwest does not know, which it skips instead of reporting.
Where this setup is used
- API clients behind an allowlisted address, where a partner accepts calls from one static IP and the service must leave through it.
- Regional checks of your own product, such as prices, search results or redirects as visitors in another country see them, with a country parameter in the proxy username.
- Monitoring from outside your network, so an uptime probe reaches your site the way a customer does.
- Command-line tools and workers inside a corporate network that reach the internet only through the company proxy, often via
HTTPS_PROXY.
Common errors and what they mean
reqwest's errors describe the stage that failed rather than give a code; print them with {:?} to see the full cause chain, and use is_connect(), is_timeout() and is_builder() to sort them.
is_builder()is true when callingProxy::all: the proxy URL did not parse. A password with unencoded#,/or@is the usual cause; encode it or use.basic_auth().- A
407response, orproxy authorization requiredin the chain of a connect error: wrong credentials, an unencoded special character, or an IP that is not on the whitelist. The causes are collected in HTTP 407 Proxy Authentication Required. is_connect()with a refused or timed-out connection: wrong host or port, or a firewall between you and the proxy. Check the port the panel shows for the protocol you chose.- A SOCKS URL that fails instantly: the
socksfeature is missing fromCargo.toml, or asocks5h://URL points at the HTTP port. Anhttp://URL aimed at the SOCKS port fails the same way. is_timeout(): thetimeoutorconnect_timeoutyou set ran out. Retry with backoff; if it keeps happening, the exit or the target is slow.- Certificate errors only behind the company network: a TLS-inspecting corporate proxy. Add its CA with
tls_certs_merge. - The proxy is not used at all: a
Proxy::http-only rule, an earlier rule that already matched, a host inNO_PROXY, or a leftoverREQUEST_METHODvariable.
Common mistakes
- Writing
https://in the proxy URL for a plain HTTP port. The scheme describes the proxy, not the target. - Expecting environment variables to still apply after
.proxy(). Adding any proxy switches them off. - No
timeouton the async client. It has no default. - Building a new client for every request. Each one starts an empty pool; build once and clone.
- Retrying a
407. The next attempt sends the same wrong credentials. - Turning certificate checks off to "fix" a proxy. Add the right CA instead.
Which approach should you choose?
| Your situation | Recommendation |
|---|---|
| One proxy, no code change | HTTPS_PROXY and HTTP_PROXY, NO_PROXY for local hosts |
| One proxy set in code | Proxy::all(url) plus timeout |
| Password with special characters | .basic_auth(user, pass) |
| SOCKS5 with DNS at the proxy | socks feature and socks5h:// |
| Internal hosts must go direct | .no_proxy(NoProxy::from_string(…)) |
| A new exit for every request | Rotating gateway, pool_max_idle_per_host(0), http1_only() |
| The same exit for a login flow | Session parameter in the username, default pool |
| Synchronous program | reqwest::blocking::Client with the blocking feature |
| Corporate proxy with its own CA | tls_certs_merge, never disabled checks |
Frequently asked questions
Does reqwest use the system proxy automatically?
Yes. Without a .proxy() call, reqwest reads HTTP_PROXY, HTTPS_PROXY, ALL_PROXY and NO_PROXY, and with the default system-proxy feature it also reads the Windows and macOS settings. Calling .proxy() or .no_proxy() on the builder turns that lookup off.
How do I disable the proxy for one reqwest client?
Call ClientBuilder::no_proxy() when building that client. It clears every proxy rule and also stops the client from reading the environment, so it always connects directly.
Does reqwest support socks5h?
Yes, with the socks feature enabled. socks5h:// lets the proxy resolve the host name, socks5:// resolves it on your machine, and socks4a:// and socks4:// follow the same split.
How do I use a proxy pool with reqwest?
Use Proxy::custom with a closure that returns the next address from your list, or point the client at a rotating gateway that changes the exit for you. In both cases a reused connection keeps its exit, so turn idle pooling off when each request needs a new IP.
Can I set a different proxy for a single request?
Not on the request itself: the proxy belongs to the Client. Build a second client for the requests that need another proxy, or decide per target host inside a Proxy::custom closure.
Why does my HTTPS request ignore the proxy?
The usual reasons are a Proxy::http rule, which never matches https:// targets, only HTTP_PROXY set without HTTPS_PROXY, or a target listed in NO_PROXY. An earlier rule that already matched and a proxy URL with an unknown scheme have the same effect.
Summary
In reqwest a proxy is a rule on the Client: Proxy::all("http://user:pass@pr.proxynet.io:8000") for one gateway, socks5h:// with the socks feature for SOCKS5, the environment variables when you set nothing in code, and NoProxy or ClientBuilder::no_proxy() for what must go direct. Encode special characters or use .basic_auth(), always set a timeout on the async client, retry network errors, 429 and 5xx with backoff but never a 407, and remember that pooled connections keep their exit until they close. Residential, mobile, static ISP and SOCKS5 endpoints that work with these settings are on the Proxynet proxy page.




