potelo / laravel-block-bots
Block bots and high traffic offenders using Redis
Requires
- php: ^7.1 || ^8.0 || ^8.1 || ^8.2 || ^8.3 || ^8.4 || ^8.5
- ext-json: *
- guzzlehttp/guzzle: ^7.5.0
- laravel/framework: ^5.5|^6.0|^7.0|^8.0|^9.0|^10.0|^11.0|^12.0|^13.0
- predis/predis: ^2.2
Requires (Dev)
- orchestra/testbench: ^7.0
- phpunit/phpunit: ^9.5
Suggests
None
Provides
None
Conflicts
None
Replaces
None
- dev-master
- 4.1.0
- 3.1
- 3.0
- 2.1.2
- 2.1.1
- 2.1.0
- 2.0.0
- 1.6.1
- 1.6.0
- 1.5.1
- 1.5.0
- 1.4.0
- 1.3.1
- 1.3.0
- 1.2.2
- 1.2.1
- 1.2.0
- 1.1.3
- 1.1.2
- 1.1.1
- 1.1.0
- 1.0.3
- 1.0.2
- 1.0.1
- 1.0.0
- 0.2.2
- 0.2.1
- 0.2.0
- 0.1.6
- 0.1.5
- 0.1.4
- 0.1.3
- 0.1.2
- 0.1.1
- 0.1.0
- dev-feat/guest-network-quotas
- dev-refactor-tratamento-bots
- dev-feature-dinamisa-ips-permitidos
This package is auto-updated.
Last update: 2026-12-02 16:47:08 UTC
README
Introduction
Laravel Block bots is a package that blocks bad crawlers, people trying to scrape your website or high-usage users, but lets good and important crawlers such as GoogleBot and Bing pass through.
Features
- ULTRA fast, less than 1ms increase in each request.
- Verify Crawlers using reverse DNS
- Highly configurable
- Redirect users to a page when they got blocked
- Apply configurable limits to authenticated users
- Native IPv6 support with prefix-based rate limiting
Install
Via Composer
composer require potelo/laravel-block-bots
Requirement
- This package relies heavily on Redis. To use it, make sure that Redis is configured and ready. (see Laravel Redis Configuration)
Before Laravel 5.5
In Laravel 5.4, you'll manually need to register the \Potelo\LaravelBlockBots\BlockBots::class service provider in config/app.php.
Config
To adjust the library, you can publish the config file to your project using:
php artisan vendor:publish --provider="Potelo\LaravelBlockBots\BlockBotsServiceProvider"
Configure variables in your .env file:
BLOCK_BOTS_ENABLED=true # Enables block bots
BLOCK_BOTS_MODE=production # Options: production, never, always
BLOCK_BOTS_USE_DEFAULT_ALLOWED_BOTS=true # Use our preset whitelist
BLOCK_BOTS_WHITELIST_KEY=block_bot:whitelist
BLOCK_BOTS_FAKE_BOTS_KEY=block_bot:fake_bots
BLOCK_BOTS_PENDING_BOTS_KEY=block_bot:pending_bots
BLOCK_BOTS_LOG_ENABLED=true # Enables log
BLOCK_BOTS_IPV6_PREFIX_LENGTH=64 # IPv6 prefix length (see below)
Usage
It's simple. Go to Kernel.php and add to the $routeMiddleware block as:
protected $routeMiddleware = [ // ... 'block' => \Potelo\LaravelBlockBots\Middleware\BlockBots::class, ];
Then you can put it in the desired groups. For example, let's set it to the web group:
protected $middlewareGroups = [ 'web' => [ // ... \App\Http\Middleware\VerifyCsrfToken::class, 'block:100,daily', // 100 requests per day. ], ];
Where:
- 100: is the number of pages an IP can access every day
- daily: is the time period. Options:
hourly,daily,weekly,monthly,annually
IPv6 Support
This package has native IPv6 support with prefix-based rate limiting.
Why Prefix-Based Rate Limiting?
IPv6 users typically receive a prefix (e.g., /64) from their ISP, giving them access to millions or trillions of unique IP addresses. Without prefix-based handling, a malicious user could easily bypass rate limits by rotating through different IPs within their allocation.
This package normalizes IPv6 addresses to their prefix for tracking:
2001:db8:1234:5678:aaaa:bbbb:cccc:dddd → 2001:db8:1234:5678::
All IPs within the same prefix are treated as a single entity for rate limiting.
Configuring IPv6 Prefix Length
Set the prefix length in your .env:
BLOCK_BOTS_IPV6_PREFIX_LENGTH=64
| Prefix | Use Case | Description |
|---|---|---|
| /64 | Standard residential (default) | Most common allocation, recommended for most cases |
| /56 | Some residential ISPs | If your users typically have /56 allocations |
| /48 | Business/enterprise | For sites primarily serving business networks |
Bot Verification with IPv6
The package also handles legitimate bots (like GoogleBot) that use IPv6:
- Original IP is used for reverse DNS verification
- Trackable prefix is used for whitelisting
- Once verified, all IPs within the bot's prefix are automatically allowed
Forward DNS must contain the exact original IPv6 address (AAAA record); another address in the same prefix is insufficient. A failed verification removes the unlimited bot exemption; normal rate limits still apply.
Change log
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING and CODE_OF_CONDUCT for details.
Credits
License
The MIT License (MIT). Please see License File for more information.
Dynamic bot IP ranges
Breaking change in 4.0: IP-managed bots are verified only by IP and their feeds are configured only in
bot_ip_provider.bots. See CHANGELOG before upgrading from 3.x.
The default configuration includes a runtime provider alongside static ranges:
'allowed_bots_by_ip' => [ \Potelo\LaravelBlockBots\Services\BotIpProvider::class, 'claudebot' => ['160.79.104.0/21'], // 'gptbot' => [], // Explicitly disable this bot's exemption. ],
BotIpProvider manages only the bots listed in bot_ip_provider.bots. The default
configuration lists GPTBot, ChatGPT-User, OAI-SearchBot and DuckAssistBot with their
feed URLs only; remove an entry to stop managing that bot, or remove the provider
from allowed_bots_by_ip to disable the feature entirely.
Before a bot's first successful refresh, its optional defaults are used. A bot
without defaults has no ranges until then, so it is not exempted (it is
treated as any other client over the limit) until the scheduler and a queue worker
fetch its feed. Successful feeds replace the defaults entirely; later failures
preserve the last successful snapshot indefinitely. Refreshes write only to Redis, never to tracked files.
Static bot arrays always override provider results, regardless of their order.
Only an explicitly configured empty static array disables an exemption; empty
remote feeds are errors. With BLOCK_BOTS_USE_DEFAULT_ALLOWED_BOTS=false,
an IP-managed bot must also match the middleware's custom bot list to receive a bot
exemption. Explicit whitelist_ips still apply.
Configuration (add, remove or edit bots; defaults is optional):
'bot_ip_provider' => [ 'schedule_enabled' => true, 'refresh_days' => 15, 'redis_prefix' => 'block_bot:ip_sources:', 'bots' => [ 'gptbot' => ['url' => 'https://openai.com/gptbot.json'], 'chatgpt-user' => ['url' => 'https://openai.com/chatgpt-user.json'], 'oai-searchbot' => ['url' => 'https://openai.com/searchbot.json'], 'duckassistbot' => ['url' => 'https://duckduckgo.com/duckassistbot.json'], 'mybot' => [ 'url' => 'https://example.com/bot.json', 'defaults' => ['192.0.2.0/24'], ], ], ],
Feeds must return HTTP 200 and JSON with nonempty prefixes, containing valid
ipv4Prefix and/or ipv6Prefix CIDRs. Invalid entries reject the entire response.
Only HTTPS endpoints are supported; redirects are rejected. Use trusted URLs.
The service class name and settings remain safe for config:cache; live ranges
are read from Redis at runtime.
The package automatically registers a daily scheduler check. To avoid waiting for
it after a deploy, run php artisan block-bots:refresh-ips --due. Run Laravel's
scheduler and an asynchronous queue worker in the consuming application.
Each source becomes due 15 days after its last successful fetch; new sources are
due immediately. Failed sources retry five additional times, after 1 minute,
5 minutes, 30 minutes, 2 hours and 12 hours. After exhaustion the next daily check
starts a new cycle. A Redis lease prevents duplicate cycles across servers;
abandoned cycles become eligible again after its two-day expiry. Use a queue
backend that supports 12-hour delays (for example Redis or database, not SQS).
# Queue immediate refreshes, including recently updated sources: php artisan block-bots:refresh-ips # Queue only new or due sources (also invoked by the scheduler): php artisan block-bots:refresh-ips --due
When changing a bot's feed URL, rebuild the configuration cache if the
application uses one, restart the queue workers, and run
php artisan block-bots:refresh-ips without --due. This queues a refresh for
each configured source without an active lease, including sources with recent
snapshots. If a source already has an active lease, its existing cycle can fetch
the new URL once the restarted worker picks up the job. If you still need to
force a refresh, run the command again after the lease is released or expires.
The bot keeps using its previous snapshot until a worker successfully fetches
the new feed.
Verification behavior and upgrade notes
Normal guest rules and rate limits still run first. When the bot exemption is needed, IP rules use the original IP, not the normalized IPv6 prefix, and run before the shared whitelist/fake-bot sets. IP-managed bots are no longer admitted while awaiting asynchronous DNS checks, nor do they populate permanent verification sets. Existing queued DNS jobs for these bots exit without writing results.
Explicit whitelist_ips entries still grant access for IP-managed bots.
Previously cached whitelist/fake-bot decisions are ignored for IP-managed requests;
no blanket deletion of shared Redis sets is performed because those sets do not
record which bot created each entry. Consequently, a removed range immediately
loses its bot exemption and a newly added range can be reconsidered on the next
request. Old shared entries retain their existing behavior for other traffic.
This also applies to static IP rules, including explicit empty overrides.
If the application already published config/block-bots.php, replace the four
moved static bot entries with BotIpProvider::class and copy the bot_ip_provider
block (including its bots list) to enable dynamic updates. Laravel merges only
top-level config keys, so a published bot_ip_provider block without a bots list
manages no bots.
To keep the previous static ranges until the first refresh, set them as defaults.
Leaving a static entry in the published configuration intentionally overrides that
bot's provider ranges. Restart long-running queue workers after deployment.
If upgrading from a version of the provider that used untagged Redis keys,
run php artisan block-bots:refresh-ips after restarting the workers. Refreshes
populate the new keys. Configured defaults, if any, apply until each refresh
succeeds.
Rate-limit responses
Unknown bots and bots that fail verification retain the normal request limit.
Requests denied above that limit receive 429 with Retry-After in seconds,
read from the actual hit counter's Redis TTL. This includes authenticated users.
The header is omitted when there is no positive TTL. Custom rule denials and
mode=always retain 429; they only get this header when the limit is exceeded.
The existing json_response and HTML view remain unchanged. Applications
overriding notAllowed() must add the header to their custom responses.
DNS verification upgrade and deployment
Configured hostname values containing a dot must match the whole PTR hostname
or a subdomain suffix: msn.com accepts crawler.search.msn.com, but rejects
msn.com.attacker.test. Values without dots retain substring matching and its
limitations; * retains its existing behavior. The default msn entry now uses
msn.com. IPv4 retains exact forward-address matching; IPv6 now requires an
exact AAAA address, comparing binary addresses to handle equivalent spellings.
DNS lookup errors propagate without adding the address to the fake-bot set;
the pending entry has been removed so a later request can enqueue another check.
Clear the existing whitelist after deploying the stricter verifier. Otherwise
entries approved by the old rules keep their exemption. Before clearing,
evaluate the number of entries (SCARD on the configured whitelist key), active
bot traffic, queue backlog, worker capacity, and DNS latency. Expect a temporary
increase in reverse and forward DNS lookups as active bots are reverified.
Use an asynchronous queue and choose a lower-traffic deployment window.
- Update published configuration, especially
allowed_bots.msntomsn.com. - Rebuild configuration caches and restart queue workers on the new code. Ensure old-version workers cannot repopulate the whitelist.
- Run
php artisan block-bots:clear-whitelist. - Monitor verification volume, queue latency/failures, DNS errors and 429 rates.
The default middleware admits recognized DNS bots while verification is pending. Applications requiring completed verification may temporarily return 429 to legitimate crawlers until their jobs finish. Static whitelist IPs are restored on evaluation; IP-range exemptions do not depend on this whitelist. The package does not clear production data automatically.
Daily guest quotas for public pages
Override the route middleware's guestQuotaLimits() to return [20, 100] on the protected pages.
The first limit applies to an IPv4 address or IPv6 /64. The second applies to the encompassing
IPv4 /24 or IPv6 /48. Returning null keeps the original policy. Authenticated users follow
the application's usual account rules. Use the framework's trusted-proxy configuration and
resolve the authentication guard before selecting the client identity.
Both counters expire at midnight in the configured timezone. A single atomic Redis call admits a
visit or returns the exhausted limit. A rejected visit does not spend the other counter's budget.
For multiple requests representing the same page, return its server-resolved identity from
guestQuotaPageKey(). Only admitted pages are deduplicated, for up to five minutes per client.
A guest quota refusal returns HTTP 429, Retry-After, Cache-Control: private, no-store and
X-BlockBots-Reason: guest-page-quota. Override block-bots::error to offer a login link.
The view receives $guestPageQuota = true. AJAX requests retain the configured JSON representation.
Use isVerifiedSearchCrawler() for a verified Googlebot or Bingbot identity. An operational IP
exemption permits access but does not identify a search engine.