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

Laravel+LiteSpeed LSCACHE:如何为已认证用户排除Admin Bar缓存?

解决Laravel集成LiteSpeed LSCACHE的认证用户缓存问题

问题1:为认证/未认证用户提供不同缓存版本

LiteSpeed依赖HTTP响应头控制缓存策略,你可以通过Laravel中间件实现用户身份的缓存区分:

  1. 创建自定义中间件
    生成SetCacheHeaders中间件:
php artisan make:middleware SetCacheHeaders

在app/Http/Middleware/SetCacheHeaders.php中编写逻辑:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

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

        if (!auth()->check()) {
            // 未认证用户:公共缓存
            $response->headers->set('Cache-Control', 'public, max-age=3600');
            $response->headers->set('X-LiteSpeed-Cache-Control', 'public, max-age=3600');
            $response->headers->set('X-LiteSpeed-Tag', 'public-page');
        } else {
            // 已认证用户:私有缓存,基于Cookie区分版本
            $response->headers->set('Cache-Control', 'private, max-age=1800');
            $response->headers->set('X-LiteSpeed-Cache-Control', 'private, max-age=1800');
            $response->headers->set('Vary', 'Cookie');
            $response->headers->set('X-LiteSpeed-Tag', 'private-page-' . auth()->id());
        }

        return $response;
    }
}
  1. 注册中间件
    在app/Http/Kernel.php的web中间件组中添加该中间件,确保它在StartSession之后执行(需读取用户认证状态):
protected $middlewareGroups = [
    'web' => [
        // ...其他中间件
        \App\Http\Middleware\StartSession::class,
        \App\Http\Middleware\SetCacheHeaders::class,
        // ...
    ],
];

配置完成后,LiteSpeed会为未认证用户存储公共缓存,为每个已认证用户生成独立的私有缓存版本,自动适配Admin Bar的显示逻辑。

问题2:不使用ESI/AJAX排除特定组件缓存

结合上述私有缓存方案,已能解决Admin Bar的缓存冲突——已认证用户的私有缓存会包含对应权限的Admin Bar,访客缓存则无该组件。

若需更精细的局部控制,可采用以下方式:

  • 保持现有Admin Bar的视图判断逻辑(基于$is_admin/$is_editor)不变
  • 确保已认证用户的缓存绑定用户ID(如问题1中X-LiteSpeed-Tag的设置),让每个用户的缓存版本完全专属,自然包含其对应的Admin Bar组件。

针对CSRF令牌问题:表单中正常使用@csrf指令即可,已认证用户的私有缓存会包含专属令牌;访客页面若涉及敏感表单,可单独对该路由禁用缓存,避免令牌固定导致的安全问题。


内容的提问来源于stack exchange,提问作者Haktan Aydın

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 15:08:29