我的 Laravel 应用程序默认为每个站点返回 Cache-Control: no-cache, private
HTTP header 。我怎样才能改变这种行为?
P.S.: 这不是 PHP.ini 问题,因为将 session.cache_limiter
更改为 empty/public 不会改变任何内容。
最佳答案
Laravel 5.6+
不再需要添加您自己的自定义中间件。
SetCacheHeaders
中间件随 Laravel 开箱即用,别名为 cache.headers
这个中间件的好处是它只适用于GET
和HEAD
请求——它不会缓存POST
或 PUT
请求,因为您几乎不想这样做。
您可以通过更新您的 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'));
}
不过我不推荐这样做。相反,与任何中间件一样,您可以轻松地应用于特定端点、组或 Controller 本身,例如:
Route::middleware('cache.headers:private;max_age=3600')->group(function() {
Route::get('cache-for-an-hour', 'MyController@cachedMethod');
Route::get('another-route', 'MyController@alsoCached');
Route::get('third-route', 'MyController@alsoAlsoCached');
});
请注意,选项由分号 而非逗号分隔,连字符由下划线代替。此外,Symfony 仅支持 a limited number of options :
'etag', 'last_modified', 'max_age', 's_maxage', 'private', 'public', 'immutable'
换句话说,您不能简单地复制和粘贴标准的 Cache-Control
header 值,您需要更新格式:
CacheControl format: private, no-cache, max-age=3600
->
Laravel/Symfony format: private;max_age=3600
关于php - Laravel 5 如何全局设置 Cache-Control HTTP header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51821563/