Laravel: detect VPN and proxy users with middleware
By Muntaha Shaheen · · updated · 8 min read
To detect VPN and proxy users in Laravel, add a middleware that sends $request->ip() to a VPN detection API such as POST https://iplogs.com/v1/check and acts on the verdict. First set trustProxies() in bootstrap/app.php to the addresses your load balancer connects from, or $request->ip() returns the load balancer or whatever the client typed into a header. Avoid trustProxies(at: '*'), which lets a client choose its own IP. Use the built-in Http client with a connect timeout and a total timeout, and cache full verdicts but never fast-mode ones. Block vpn_detected and flagged proxies that are not privacy relays on routes such as registration, login or checkout. If the API fails, times out or answers 429, return no verdict and let the request through, so an outage never locks anyone out. Attach the middleware only to routes where an anonymous network changes the risk, not to every page view.
Score to verdict to handling
- clean below 0.30
- Allow.
- suspicious 0.30 to 0.60
- Allow. Log it, maybe require email verification.
- vpn_likely 0.60 to 0.85
- Step up: CAPTCHA, verification or manual review.
- vpn_detected 0.85 and above
- Block on signup or checkout, or step up on login.
A VPN check in Laravel is a middleware plus a small service class that posts the visitor's address to a detection API. The HTTP call itself is a few lines. Most of the care goes into trustProxies(), which decides whose address $request->ip() returns once a load balancer sits in front of the app, and into the timeout and cache wrapped around the call, so a slow API can't hold up the signup form and repeat visitors don't eat into a rate limit.
Everything here is for Laravel 11 and newer, 12 and 13 included, where middleware and trusted proxies are set up in bootstrap/app.php rather than in the HTTP kernel older versions used.
How do I detect a VPN in Laravel?
Send each visitor's IP from a middleware to a detection API and act on the verdict it returns. That takes four pieces, and the first one decides whether the other three see the right address:
- Tell Laravel which proxies it sits behind, with
trustProxies()inbootstrap/app.php. - Write an
IpCheckservice that posts the IP tohttps://iplogs.com/v1/check, with a connect and a total timeout. - Cache full answers for 15 minutes (never fast-mode ones) and back off when the API answers 429.
- Add a
block.anonymousmiddleware to registration, login or checkout routes. Blockvpn_detectedand flagged proxies that aren't privacy relays, pass everything else through and let the controller add friction for grey cases.
Why does $request->ip() return my load balancer's address?
Because the TCP connection comes from the load balancer, and Laravel only reads X-Forwarded-For from proxies you have told it to trust. Until you do, $request->ip() is the proxy's address, and every visitor gets the same verdict: whatever your load balancer's network looks like.
List the addresses your proxy connects from. On a private network that is usually one range:
// bootstrap/app.php
->withMiddleware(function (Middleware $middleware): void {
// Only the addresses your load balancer connects from.
$middleware->trustProxies(at: ['10.0.0.0/8']);
})With that in place, Laravel (through Symfony's Request class) walks the X-Forwarded-For chain from the right, drops every address that belongs to a trusted proxy, and returns the first one that doesn't. For a chain of 1.2.3.4, 198.51.100.9 arriving from 10.0.0.5, the answer is 198.51.100.9: the address your own proxy saw. The 1.2.3.4 on the left was written by the client and is ignored.
The request docs say IP addresses "should be considered untrusted, user-controlled input." The rate limiter examples in Laravel's routing docs key on $request->ip() as well, so a wrong proxy setting reaches your throttling too: either every visitor shares the load balancer's bucket, or a client that controls the header gets a new bucket on every request.
Why trustProxies(at: '*') breaks VPN detection
The docs suggest '*' for cloud load balancers whose addresses you don't know. In Laravel's TrustProxies middleware, '*' trusts 0.0.0.0/0 and ::/0, so every hop counts as a proxy. When nothing in the chain is untrusted, Symfony falls back to the first, leftmost entry, which is the one the client controls. Anyone can then send X-Forwarded-For: <a clean home IP> and pass your check, even when connecting directly to the server.
A feature test shows the difference. With at: ['10.0.0.0/8'] it passes; switch the config to '*' and it fails, because ip() now returns 1.2.3.4:
// tests/Feature/ClientIpTest.php
public function test_a_direct_client_cannot_choose_its_ip(): void
{
// A throwaway route for this test only; it never goes in routes/web.php.
Route::get('/whoami', fn (Request $request) => $request->ip());
$this->withServerVariables(['REMOTE_ADDR' => '203.0.113.7'])
->withHeaders(['X-Forwarded-For' => '1.2.3.4'])
->get('/whoami')
->assertSeeText('203.0.113.7');
}On AWS, if you don't know the balancer's exact addresses, trust your VPC's CIDR instead of '*'. Requests from the balancer arrive from inside that range, and no outside client can connect from it.
Laravel behind Cloudflare
Cloudflare sends the visitor's address in CF-Connecting-IP and adds whichever address connected to it to the end of X-Forwarded-For. Trust Cloudflare's published ranges, plus 127.0.0.1 if a local nginx proxies to Octane or another app server. Keep the ranges in a file so you can refresh them:
{ curl -s https://www.cloudflare.com/ips-v4; echo; curl -s https://www.cloudflare.com/ips-v6; echo; } > bootstrap/cloudflare-ips.txt$middleware->trustProxies(at: [
'127.0.0.1',
...file(__DIR__.'/cloudflare-ips.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES),
]);Don't read the trusted proxy list from env() in bootstrap/app.php. Once you run php artisan config:cache, Laravel stops loading .env, so env() only sees real system environment variables and a value set in .env comes back as null.
How do I call a VPN detection API from Laravel?
Use the built-in Http client with an explicit connect timeout and total timeout, and treat any failure as "no answer". This service returns the decoded verdict, or null when it has nothing to say:
<?php
namespace App\Services;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
class IpCheck
{
private const ENDPOINT = 'https://iplogs.com/v1/check';
private const BACKOFF_KEY = 'iplogs:backoff';
/**
* The iplogs verdict for $ip, or null when no answer is available.
* Callers treat null as "allow".
*/
public function verdict(string $ip): ?array
{
if (Cache::has(self::BACKOFF_KEY)) {
return null;
}
$key = "iplogs:{$ip}";
if (is_array($cached = Cache::get($key))) {
return $cached;
}
try {
$response = Http::connectTimeout(2)
->timeout(5)
->acceptJson()
->post(self::ENDPOINT, ['ip' => $ip]);
if ($response->status() === 429) {
$wait = (int) $response->header('Retry-After') ?: 60;
Cache::put(self::BACKOFF_KEY, true, $wait);
}
// Throws on 4xx/5xx, so failures never reach the cache.
$data = $response->throw()->json();
} catch (ConnectionException|RequestException $e) {
Log::warning('iplogs check failed, allowing request', [
'ip' => $ip,
'error' => $e->getMessage(),
]);
return null;
}
if (! is_array($data)) {
return null;
}
// A fast answer is the in-memory one sent once the daily quota is
// spent: use it, but don't keep it.
if (($data['mode'] ?? null) !== 'fast') {
Cache::put($key, $data, now()->addMinutes(15));
}
return $data;
}
/**
* A VPN or Tor exit, or an open or residential proxy. Privacy relays
* (iCloud Private Relay, Cloudflare WARP) report is_relay and pass, even
* though WARP alone scores vpn_detected.
*/
public static function shouldBlock(?array $verdict): bool
{
if (! empty($verdict['is_relay'])) {
return false;
}
return ($verdict['verdict'] ?? null) === 'vpn_detected' || ! empty($verdict['is_proxy']);
}
}Left alone, Laravel's client waits 10 seconds to connect and 30 seconds in total, which is a long time to leave someone looking at a submit button. connectTimeout(2) and timeout(5) cap the wait; when either runs out the client throws ConnectionException, and the catch turns it into null. A first full check of an address the API hasn't seen takes about 3 seconds (its ceiling is 8), so a few lookups hit the limit and fail open.
The throw() call covers a quieter failure. The Http client returns 4xx and 5xx responses as ordinary response objects, so without it an error body would be decoded and cached as though it were a verdict. With it, a RequestException reaches the catch before anything is stored, and the next request tries again. A body that isn't a JSON object counts as no answer, and an answer whose mode is fast is used but not cached. The cache calls sit outside the try: if your cache store can go down, catch its errors too, or a cache outage becomes a 500.
A 429 takes the same exit with one extra step. The API sends it with a Retry-After header once a caller passes 60 requests a minute, and the service writes iplogs:backoff to the cache for that many seconds; while the key exists, verdict() returns null without making a call. The middleware reads null as "allow", so an outage on the API's side means a few unchecked signups, and nobody gets locked out.
How do I block VPN users on specific Laravel routes?
Generate a middleware, inject the service, and attach the middleware only to the routes where an anonymous network changes the risk. Page views and API reads rarely need it.
php artisan make:middleware BlockAnonymousIps<?php
namespace App\Http\Middleware;
use App\Services\IpCheck;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class BlockAnonymousIps
{
public function __construct(private IpCheck $ipCheck)
{
}
public function handle(Request $request, Closure $next): Response
{
$ip = $request->ip();
$result = $ip ? $this->ipCheck->verdict($ip) : null;
if (IpCheck::shouldBlock($result)) {
abort(403, 'Please turn off your VPN or proxy and try again.');
}
// Controllers can add friction for the grey cases.
$request->attributes->set('ip_verdict', $result);
return $next($request);
}
}Laravel resolves middleware through the service container, so the constructor injection works without any binding. Register an alias next to your proxy settings and use it on routes:
// bootstrap/app.php
use App\Http\Middleware\BlockAnonymousIps;
->withMiddleware(function (Middleware $middleware): void {
$middleware->trustProxies(at: ['10.0.0.0/8']);
$middleware->alias([
'block.anonymous' => BlockAnonymousIps::class,
]);
})
// routes/web.php
Route::post('/register', [RegisteredUserController::class, 'store'])
->middleware('block.anonymous');In the controller, $request->attributes->get('ip_verdict') gives you the full response for the cases you didn't block. When is_vpn is true but the address wasn't blocked, one option is to create the account but hold it until the email address is verified.
Which verdicts should a Laravel app block?
Block the top band and flagged proxies, and add friction below it. The response carries a score from 0 to 1 and a verdict derived from it:
| verdict | score | Suggested handling |
|---|---|---|
| clean | below 0.30 | Allow. |
| suspicious | 0.30 to 0.60 | Allow. Log it, maybe require email verification. |
| vpn_likely | 0.60 to 0.85 | Step up: CAPTCHA, verification or manual review. is_vpn is true from here. |
| vpn_detected | 0.85 and above | Block on signup or checkout, or step up on login. |
Independently of the band, shouldBlock() also refuses an address the API flags is_proxy (open proxies and residential-proxy exits). A privacy relay (is_relay) always passes, which matters for Cloudflare WARP: its addresses score 0.85 on their own.
A hard block on everything above clean would turn away Safari users who have iCloud Private Relay switched on and staff working through a company VPN, and those people are usually legitimate. The opposite mistake is reading clean as proof of a home connection. Residential proxy exits are close to undetectable from the IP alone, so whatever fraud controls you already have should stay.
How many checks can a Laravel app make for free?
Sixty a minute and 2,000 full checks per UTC day, shared by the whole app, since every call leaves from your server's IP. There's no key or sign-up. Once the daily figure is used up the API keeps answering with HTTP 200, but in fast mode, without the live probes. The 15-minute cache does most of the work of staying under those numbers: ten attempts at the signup form from one address cost one lookup.
Login is where latency hurts, since every attempt waits on the answer. Adding 'mode' => 'fast' to the request body is computed from in-memory data in microseconds (the network round trip still applies) without the live probes, so it catches fewer unlisted VPNs. verdict() never caches a fast answer, so a full one can replace it later. Existing users can be screened from a queued job with POST /v1/bulk-check, which takes up to 100 IPs per call, each counting against the 2,000 daily full checks; the job should send at most three calls in a burst and then one every 5 seconds.
How do I test VPN detection in Laravel?
Http::fake() keeps the tests off the network. The case most worth covering is the API being unreachable, which Http::failedConnection() simulates:
<?php
namespace Tests\Feature;
use App\Services\IpCheck;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;
class IpCheckTest extends TestCase
{
public function test_it_returns_the_verdict(): void
{
Http::fake(['iplogs.com/*' => Http::response(['verdict' => 'vpn_detected', 'is_vpn' => true])]);
$this->assertSame('vpn_detected', app(IpCheck::class)->verdict('192.0.2.10')['verdict']);
}
public function test_it_fails_open_when_the_api_is_unreachable(): void
{
Http::fake(['iplogs.com/*' => Http::failedConnection()]);
$this->assertNull(app(IpCheck::class)->verdict('192.0.2.11'));
}
public function test_it_backs_off_after_a_429(): void
{
Http::fake(['iplogs.com/*' => Http::response('', 429, ['Retry-After' => '30'])]);
$this->assertNull(app(IpCheck::class)->verdict('192.0.2.12'));
$this->assertTrue(Cache::has('iplogs:backoff'));
}
public function test_a_fast_answer_is_not_cached(): void
{
Http::fake(['iplogs.com/*' => Http::response(['verdict' => 'clean', 'mode' => 'fast'])]);
app(IpCheck::class)->verdict('192.0.2.13');
$this->assertFalse(Cache::has('iplogs:192.0.2.13'));
}
public function test_should_block(): void
{
$this->assertTrue(IpCheck::shouldBlock(['verdict' => 'vpn_detected']));
$this->assertTrue(IpCheck::shouldBlock(['verdict' => 'vpn_likely', 'is_proxy' => true]));
$this->assertFalse(IpCheck::shouldBlock(['verdict' => 'suspicious', 'is_proxy' => true, 'is_relay' => true]));
$this->assertFalse(IpCheck::shouldBlock(['verdict' => 'vpn_detected', 'is_relay' => true])); // WARP
$this->assertFalse(IpCheck::shouldBlock(null));
}
}To see a live response, call the service from php artisan tinker. On 27 October 2026 192.42.116.44 was a published Tor exit relay, and the result, abridged, looked like this:
> app(\App\Services\IpCheck::class)->verdict('192.42.116.44');
= [
"score" => 1,
"verdict" => "vpn_detected",
"is_vpn" => true,
"is_proxy" => true,
"signals" => [["type" => "tor_exit", "weight" => 0.95, "matched" => true, ...], ...],
"ip_info" => ["ip" => "192.42.116.44", "asn" => "AS215125", "country_code" => "NL", "vpn_provider" => "Tor", ...],
]Opening the app in a browser through php artisan serve tells you little, because the client IP there is 127.0.0.1 and a loopback address has nothing to classify. Pass real addresses to the service, as above.
Questions people also ask
Does Laravel have built-in VPN detection?
No. $request->ip() and $request->ips() return addresses, and the rate limiter can count requests per address, but nothing in the framework knows whether an address belongs to a VPN, a proxy or a Tor exit. That takes an IP intelligence API or dataset.
Should I check every request for a VPN?
No. Attach the middleware to registration, login, checkout or posting content, where an anonymous network changes the risk. Ordinary page views then carry no extra latency, and the per-minute API limit goes much further.
Why does every check in my Laravel app return the same IP?
No trusted proxies are configured, so $request->ip() is returning the load balancer. Add the balancer's addresses with $middleware->trustProxies(at: [...]) in bootstrap/app.php.
Is it safe to use trustProxies(at: '*')?
Not for anything security-related. With '*' every hop is trusted, so $request->ip() falls back to the leftmost X-Forwarded-For entry, which the client controls. Trust your load balancer's range or your VPC CIDR instead.
Can I run the check in a queued job instead?
Yes. Store the IP with the new account, dispatch a job that calls the IpCheck service, and flag or hold the account if IpCheck::shouldBlock() is true for the verdict. The signup request then never waits on the API.
Sources
- Laravel 13.x docs: HTTP Requests (request IP, trusted proxies)
- Laravel 13.x docs: Middleware
- Laravel 13.x docs: HTTP Client (timeouts, exceptions, faking)
- Laravel 13.x docs: Cache
- Laravel 13.x docs: Configuration (config caching and env())
- Laravel 13.x docs: Routing (rate limiting)
- Laravel framework source: TrustProxies middleware
- Symfony source: HttpFoundation Request (client IP filtering)
- Symfony docs: How to configure Symfony behind a load balancer or reverse proxy
- Cloudflare docs: Cloudflare HTTP headers
- Cloudflare IP ranges