我的Laravel应用程序默认为每个站点返回Cache-Control: no-cache, private
HTTP头。我该如何更改这个行为?
P.S.:这不是PHP.ini的问题,因为将session.cache_limiter
更改为empty/public并没有改变什么。
我的Laravel应用程序默认为每个站点返回Cache-Control: no-cache, private
HTTP头。我该如何更改这个行为?
P.S.:这不是PHP.ini的问题,因为将session.cache_limiter
更改为empty/public并没有改变什么。
现在不再需要添加自定义中间件了。
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'));
}
我不建议这样做。相反,就像任何中间件一样,您可以轻松地应用于特定的端点、组或控制器本身内部,例如:
我不推荐那样做。而是像任何中间件一样,你可以很容易地应用到特定的端点、组或者是在控制器本身内部中使用,例如:
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仅支持有限数量的选项:
'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
你可以设置一个全局中间件来实现这个功能。例如:
<?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;
}
}
然后只需在Kernel文件中将其注册为全局中间件:
protected $middleware = [
....
\App\Http\Middleware\CacheControl::class
];
如果您希望写更少的代码,这里有另一种方法可以在不添加额外步骤的情况下向响应添加标头。
在上面的例子中,我创建了一个中间件,以防止路由被缓存在最终用户浏览器中。
<?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",
]);
}
}
来源:将标头附加到响应中
Route::middleware
示例。虽然只列出了一个路由,但它在一个组内,你可以添加更多。 - andrewtwebergroup()
调用之前链接中间件。 - andrewtweber