默认情况下,我的Laravel应用程序为每个站点返回Cache-Control: no-cache, private HTTP头。我如何才能改变这种行为?
附注:这不是公共问题,因为将session.cache_limiter更改为空/ PHP.ini不会更改任何内容。
发布于 2018-08-13 19:56:17
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;
}
}然后在内核文件中将其注册为全局中间件:
protected $middleware = [
....
\App\Http\Middleware\CacheControl::class
];发布于 2019-07-18 02:33:46
Laravel 5.6+
不再需要添加您自己的自定义中间件。
Laravel的SetCacheHeaders中间件开箱即用,别名为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'));
}不过,我不推荐这样做。相反,与任何中间件一样,您可以轻松地应用于特定的端点、组或控制器本身,例如:
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标头值,您需要更新格式:
CacheControl format: private, no-cache, max-age=3600
->
Laravel/Symfony format: private;max_age=3600发布于 2020-03-13 21:56:42
对于寻求编写更少代码的人来说,这里有另一种方法,可以在不需要额外步骤的情况下向响应添加报头。
在上面的示例中,我创建了一个中间件来防止路由被缓存在最终用户浏览器中。
<?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",
]);
}
}https://stackoverflow.com/questions/51821563
复制相似问题