effilib / laravel-restrict-ip-middleware
A Laravel package to restrict access by IP addresses, CIDR ranges, route names, or URI patterns.
Package info
github.com/effilib/laravel-restrict-ip-middleware
pkg:composer/effilib/laravel-restrict-ip-middleware
Requires
- php: ^8.1
- illuminate/support: ^10.0 || ^11.0 || ^12.0
Requires (Dev)
README
A Laravel middleware package to restrict access based on:
- Exact IP addresses
- CIDR ranges
- Route names (supports wildcards)
- URI patterns
This allows you to secure sensitive areas of your application, while still defining exception rules (whitelisted routes or URIs that always stay accessible).
๐ฆ Installation
Install via Composer:
composer require effilib/laravel-restrict-ip-middleware
Laravel will auto-discover the service provider.
โ๏ธ Publish Configuration
Publish the configuration file:
php artisan vendor:publish --provider="Effilib\RestrictIp\Providers\RestrictIpServiceProvider" --tag=config
This will create:
config/effilib-restrict-ip.php
๐ Usage
Apply the middleware to routes or groups.
Default ruleset
use Effilib\RestrictIp\Middleware\RestrictIpMiddleware; Route::get('/admin', fn () => 'Admin Area') ->middleware(RestrictIpMiddleware::class);
Custom ruleset
Route::get('/custom', fn () => 'Special Area') ->middleware(RestrictIpMiddleware::class . ':custom');
The middleware parameter (:custom) selects which ruleset from effilib-restrict-ip.php to apply.
๐ Configuration
Example config/effilib-restrict-ip.php:
return [ // HTTP status code when access is denied 'error_code' => 403, 'rules' => [ // Default ruleset 'default' => [ // Allowed exact IPs 'allowed_ips' => [ '127.0.0.1', '::1', ], // Allowed CIDR ranges 'allowed_cidrs' => [ // '192.168.0.0/24', ], // Exception: always allow these route names (supports wildcards) 'allowed_routes' => [ // 'healthcheck', // 'api.*', ], // Exception: always allow these URI patterns 'allowed_uri_patterns' => [ // 'status*', // 'public/*', ], ], // Example custom ruleset 'custom' => [ 'allowed_ips' => ['10.0.0.1'], 'allowed_uri_patterns' => ['public-reports/*'], ], ], ];
๐ How it works
The middleware checks in this order:
- Allowed route names โ if matched, always allowed
- Allowed URI patterns โ if matched, always allowed
- Exact IP addresses โ if matched, allowed
- CIDR ranges โ if matched, allowed
- Otherwise denied โ returns configured error code (default:
403)
๐งช Example
// routes/web.php use Effilib\RestrictIp\Middleware\RestrictIpMiddleware; Route::middleware([RestrictIpMiddleware::class])->group(function () { Route::get('/admin', fn () => 'Admin dashboard'); Route::get('/settings', fn () => 'System settings'); }); // Healthcheck route always accessible Route::get('/healthcheck', fn () => 'OK') ->name('healthcheck');
With this setup:
/adminand/settingsrequire a matching IP or CIDR
๐ License
MIT License ยฉ Effilib