You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 11如何完全移除Set-Cookie响应头(XCSRF+会话)

在Laravel 11.x中彻底移除Session和XSRF的Set-Cookie响应头

针对Laravel 11的架构变化,你可以通过以下步骤完全清除Set-Cookie头,解决CDN缓存穿透问题:

1. 全局禁用Session与CSRF相关中间件(全站点静态/可缓存场景)

Laravel 11默认在bootstrap/app.php中自动注册核心中间件,你可以直接通过withoutMiddleware方法从根源上移除所有Session和CSRF相关中间件,阻止Cookie生成:

// bootstrap/app.php
return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->without([
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class,
        ]);
    })
    ->create();

2. 针对特定路由移除(混合场景,部分路由需保留Session)

如果站点存在动态路由需要Session,仅需对静态/可缓存路由清除Set-Cookie头,按以下步骤操作:

步骤2.1 编写后置清除中间件

自定义中间件需作为后置中间件执行(响应返回客户端前最后处理),确保完全清空Set-Cookie头和Cookie队列:

// app/Http/Middleware/RemoveSessionCookies.php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class RemoveSessionCookies
{
    public function handle(Request $request, Closure $next): Response
    {
        $response = $next($request);

        // 移除所有Set-Cookie响应头
        $response->headers->remove('Set-Cookie');
        // 重置响应的Cookie容器,防止Laravel后续再添加Cookie
        $response->setCookies([]);

        return $response;
    }
}

步骤2.2 注册并应用中间件

在bootstrap/app.php中注册中间件,确保它是全局中间件的最后一项,或仅绑定到特定路由组:

// bootstrap/app.php
->withMiddleware(function (Middleware $middleware) {
    // 全局后置执行,确保最后处理响应
    $middleware->append(\App\Http\Middleware\RemoveSessionCookies::class);

    // 或创建路由组专用中间件
    $middleware->group('cacheable', [
        \App\Http\Middleware\RemoveSessionCookies::class,
    ]);
})

在路由中绑定使用:

// routes/web.php
Route::middleware('cacheable')->group(function () {
    Route::get('/static-page', [StaticController::class, 'show']);
    // 其他可缓存路由...
});

3. 验证中间件执行状态

在自定义中间件中添加日志,确认是否生效:

// 在RemoveSessionCookies的handle方法中
\Illuminate\Support\Facades\Log::info('Cookie清除中间件已执行,路由:' . $request->path());

请求目标路由后,查看storage/logs/laravel.log中的日志记录,确认中间件正常运行。

额外提示

为确保CDN正常缓存,需给可缓存路由添加正确的缓存响应头:

// 控制器方法中设置
return response()->view('static-page')->header('Cache-Control', 'public, max-age=86400');

内容的提问来源于stack exchange,提问作者Ika Balzam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 14:11:10