Laravel 5如何全局设置Cache-Control HTTP标头

che*_*ier 5 php http http-headers laravel laravel-5

我的Laravel应用程序Cache-Control: no-cache, private默认为每个站点返回HTTP标头。我该如何改变这种行为?

PS:这不是PHP.ini问题,因为更改session.cache_limiter为空/公共不会更改任何内容。

Kha*_*jan 8

Laravel 5.5 <

您可以为此使用全局中间件。就像是:

<?php

namespace App\Http\Middleware;

use Closure;

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

        $response->header('Cache-Control', 'no-cache, must-revalidate');
        // Or whatever you want it to be:
        // $response->header('Cache-Control', 'max-age=100');

        return $response;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后只需将其注册为内核文件中的全局中间件即可:

protected $middleware = [
    ....
    \App\Http\Middleware\CacheControl::class
];
Run Code Online (Sandbox Code Playgroud)


and*_*ber 6

Laravel 5.6+

不再需要添加您自己的自定义中间件。

SetCacheHeaders中间件带有Laravel箱,别名为出cache.headers

这个中间件的好处是它仅适用于GETHEAD请求-它不会缓存POSTPUT请求,因为您几乎从不希望这样做。

您可以通过更新以下内容轻松地在全球范围内应用此功能RouteServiceProvider

protected function mapWebRoutes()
{
    Route::middleware('web')
        ->middleware('cache.headers:private;max_age=3600') // added this line
        ->namespace($this->namespace)
        ->group(base_path('routes/web.php'));
}

protected function mapApiRoutes()
{
    Route::prefix('api')
        ->middleware('api')
        ->middleware('cache.headers:private;max_age=3600') // added this line
        ->namespace($this->namespace)
        ->group(base_path('routes/api.php'));
}
Run Code Online (Sandbox Code Playgroud)

我不建议这样做。相反,与任何中间件一样,您可以轻松地将其应用于特定的端点,组或控制器本身,例如:

Route::middleware('cache.headers:private;max_age=3600')->group(function() {
    Route::get('cache-for-an-hour', 'MyController@cachedMethod');
});
Run Code Online (Sandbox Code Playgroud)

请注意,选项用分号而不是逗号分隔,连字符用下划线代替。此外,Symfony仅支持有限数量的选项

'etag', 'last_modified', 'max_age', 's_maxage', 'private', 'public', 'immutable'

换句话说,您不能简单地复制和粘贴标准Cache-Control标题值,就需要更新格式:

CacheControl format:       private, no-cache, max-age=3600
  ->
Laravel/Symfony format:    private;max_age=3600
Run Code Online (Sandbox Code Playgroud)


Anw*_*war 5

对于寻求编写更少代码的方法的人来说,这是另一种无需额外步骤即可向响应添加标头的方法。

在上面的示例中,我创建了一个中间件来防止路由缓存在最终用户浏览器中。

<?php

class DisableRouteCache
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request)->withHeaders([
            "Pragma" => "no-cache",
            "Expires" => "Fri, 01 Jan 1990 00:00:00 GMT",
            "Cache-Control" => "no-cache, must-revalidate, no-store, max-age=0, private",
        ]);
    }
}
Run Code Online (Sandbox Code Playgroud)

来源:将标头附加到响应