web-dev-qa-db-ja.com

Apacheにはmod_expiresもmod_headersもありません。images/ js / cssファイルをキャッシュするにはどうすればよいですか?

タイトルはそれをすべて言います、私たちは私たちのサーバー環境を制御することはできませんし、彼らにApacheを再コンパイルするよう要求することはできますが、それは一晩では起こりません。

これらのモジュール(mod_expires、mod_headers)を使用して特定のコンテンツ(画像、js、css)をキャッシュするか、運が悪いのかを指定するのに役立つことはありませんか?

6
Chris

1つのオプションは、PHPスクリプトを介してそれらを送信し、そのスクリプトでヘッダーをキャッシュすることです。 PHPがプロキシとしてイメージを提供する必要があるため、わずかな余分なオーバーヘッドで同じことを実現します。

例:

HTML:
<img src="/images/img.php?img=someimage.png">

PHP:
<?php
    $filename = $_GET['img'];
    $file = '/path/to/file/' . $filename;

    // Do verification that the file exists, they're not after any secure 
    // files, etc. Not shown here   

    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename=' . basename($file));
    header('Content-Transfer-Encoding: binary');
    header("Last-Modified: " . date( "D, j M Y H:i:s", strtotime("- 1 month")));
    header("Expires: Thu, 20 Sep 2012 05:00:00 GMT");
    header("Cache-Control: max-age=2692000, public"); 
    header("Pragma: cache"); 
    ob_clean();
    flush();
    readfile($file);
    exit;

?>
6
John Conde