laravel-restrict-ip-middleware maintained by effilib
Laravel Restrict IP Middleware
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