Laravel 11.3.0无kernel.php时IP拦截配置及中间件注册报错解决
Laravel 11.3.0 配置IP拦截及中间件注册报错解决方法
Laravel 11移除了传统的kernel.php文件,中间件配置统一移至bootstrap/app.php。你当前的报错是因为重复调用了withMiddleware方法,且第二次传入了数组参数——withMiddleware仅接受回调函数作为参数,不能直接传数组。
一、编写IP拦截中间件
首先确保你的BlockIpMiddleware逻辑正确,示例代码如下:
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response; class BlockIpMiddleware { // 定义需要拦截的IP列表 protected $blockedIps = [ '192.168.1.100', '127.0.0.1', // 测试用,可根据实际需求修改 ]; public function handle(Request $request, Closure $next): Response { if (in_array($request->ip(), $this->blockedIps)) { abort(403, '您的IP地址已被禁止访问'); } return $next($request); } }
二、正确注册中间件
将中间件注册到bootstrap/app.php的现有withMiddleware回调中,无需额外调用withMiddleware方法。根据需求选择两种注册方式:
方式1:全局生效(拦截所有请求)
在withMiddleware回调中使用$middleware->append()添加全局中间件:
<?php use Illuminate\Foundation\Application; use Illuminate\Foundation\Configuration\Exceptions; use Illuminate\Foundation\Configuration\Middleware; return Application::configure(basePath: dirname(__DIR__)) ->withRouting( web: __DIR__.'/../routes/web.php', commands: __DIR__.'/../routes/console.php', health: '/up', ) ->withMiddleware(function (Middleware $middleware) { // 全局中间件:拦截所有请求 $middleware->append(\App\Http\Middleware\BlockIpMiddleware::class); $middleware->web(append: [ \App\Http\Middleware\HandleInertiaRequests::class, \Illuminate\Http\Middleware\AddLinkHeadersForPreloadedAssets::class, ]); $middleware->alias([ 'role' => \Spatie\Permission\Middleware\RoleMiddleware::class, 'permission' => \Spatie\Permission\Middleware\PermissionMiddleware::class, 'role_or_permission' => \Spatie\Permission\Middleware\RoleOrPermissionMiddleware::class, ]); return $middleware; }) ->withExceptions(function (Exceptions $exceptions) { // }) ->create();
方式2:仅Web路由生效
如果只需要拦截web路由组的请求,将中间件添加到web组的append数组中:
$middleware->web(append: [ \App\Http\Middleware\HandleInertiaRequests::class, \Illuminate\Http\Middleware\AddLinkHeadersForPreloadedAssets::class, \App\Http\Middleware\BlockIpMiddleware::class, // 加入此处 ]);
三、验证效果
启动Laravel服务后,使用被拦截的IP访问网站,会直接返回403错误页面,说明拦截规则已生效。
内容的提问来源于stack exchange,提问作者Mafumu
相关产品推荐
相关产品推荐

