簡體   English   中英

無法在Laravel 4中設置Cache-Control

[英]Cannot set Cache-Control in Laravel 4

我在Laravel 4中編寫了一個控制器來提供靜態資源,例如帶有一些應用程序級跟蹤的圖像文件。 我不希望人們不得不經常為每個圖像點擊Web服務器,所以我試圖設置一個Cache-Control頭。 我在這里結束了我的智慧,它顯然不起作用,我無法弄清楚原因。 有人可以看看以下內容並告訴我我做錯了什么嗎?

$headers = array(
    'Content-Type' => 'image/png',
    'Cache-Control' => 'public, max-age=300',
    'Content-Length' => filesize($file),
    'Expires' => date('D, d M Y H:i:s ', time() + 300).'GMT',
);
return Response::stream(function() use ($file) {
    readfile($file); }, 200, $headers);

當我訪問該文件時,它幾乎完美地工作。 顯示圖像,當我進入並使用Chrome或Firefox檢查元素時,我可以看到Expires標頭設置正確(當我更改它並強制重新加載時,它會適當地重置它)。 但無論我嘗試什么,Cache-Control標頭總是設置為“no-cache,private”。 我嘗試過使用以下內容,但都無濟於事:

$headers['Cache-Control'] = 'public, max-age=300'; // Original setting
$headers['cache-control'] = 'public, max-age=300'; // Case-sensitive?
$headers['Cache-Control'] = 'max-age=300';
$headers['Cache-Control'] = 'private, max-age=300';
$headers['Cache-Control'] = 'max-age=300, public';
$headers['Cache-Control'] = 'max-age=300, private';

但就像我說的那樣,無論我將它設置為什么,它總是會返回一個響應頭,顯示Cache-Control:no-cache,private。

我究竟做錯了什么? 如何通過此控制器返回我的圖像和二進制文件進行緩存? 由於某些原因,Laravel 4是否在所有響應中對Cache-Control標頭進行了硬編碼?

看到這個問題: https//github.com/symfony/symfony/issues/6530和這一行: https//github.com/symfony/symfony/blob/2.4/src/Symfony/Component/HttpFoundation/StreamedResponse.php #L87

它建議使用BinaryFileResponse。 像這樣的東西:

$response = new Symfony\Component\HttpFoundation\BinaryFileResponse($file);
$response->setContentDisposition('inline');
$response->setTtl(300);
return $response;

//Or with setting the headers manually
return  new Symfony\Component\HttpFoundation\BinaryFileResponse($file, 200, $headers, true, 'inline');

現在您可以設置Cache-Control標頭。

或使用Response :: download()外觀:

return Response::download($file)->setTtl(300)->setContentDisposition('inline');
return Response::download($file, null, $headers)->setContentDisposition('inline');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM