使所有js和css文件通过php

时间:2017-07-27 09:07:50

标签: php .htaccess

我有一个不启用mod_expires的共享主机。所以我试图让我的所有CSS和JS文件都通过一个PHP文件来添加一个必需的标题,但我无法让它工作。我尝试了this site上给出的解决方案。

我有以下内容:

htaccess的:

RewriteEngine On

RewriteCond %{QUERY_STRING} base64_encode[^(]*\([^)]*\) [OR]
RewriteCond %{QUERY_STRING} (<|%3C)([^s]*s)+cript.*(>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})
RewriteRule .* index.php [F]

RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteCond %{REQUEST_URI} !^/index\.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php [L]

RewriteRule ^(.*\.js) gzip.php?type=js&file=$1
RewriteRule ^(.*\.css) gzip.php?type=css&file=$1

PHP

<?php
$allowed = array('css','js'); //set array of allowed file types to prevent abuse

//check for request variable existence and that file type is allowed
if(isset($_GET['file']) && isset($_GET['type']) && in_array(substr($_GET['file'],strrpos($_GET['file'],'.')+1), $allowed)){
    $data = file_get_contents(dirname(__FILE__).'/'.$_GET['file']); // grab the file contents

    $etag = '"'.md5($data).'"'; // generate a file Etag
    header('Etag: '.$etag); // output the Etag in the header

    // output the content-type header for each file type
    switch ($_GET['type']) {
        case 'css':
            header ("Content-Type: text/css; charset: UTF-8");
        break;

        case 'js':
            header ("Content-Type: text/javascript; charset: UTF-8");
        break;
    }

    header('Cache-Control: max-age=300, must-revalidate'); //output the cache-control header
    $offset = 60 * 60;
    $expires = 'Expires: ' . gmdate('D, d M Y H:i:s',time() + $offset) . ' GMT'; // set the expires header to be 1 hour in the future
    header($expires); // output the expires header

    // check the Etag the browser already has for the file and only serve the file if it is different
    if ($etag == $_SERVER['HTTP_IF_NONE_MATCH']) {
        header('HTTP/1.1 304 Not Modified');
        header('Content-Length: 0');
    } else {
        echo $data;
    }
}
?>

但由于某种原因,它无法正常工作。

0 个答案:

没有答案