[英]Laravel 5 how to set Cache-Control HTTP header globally?
我的 Laravel 應用程序默認為每個站點返回Cache-Control: no-cache, private
HTTP header。 我怎樣才能改變這種行為?
PS:這不是 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;
}
}
然后只需將其注冊為內核文件中的全局中間件:
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",
]);
}
}
來源: 將標題附加到響應
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.