我无法缓存我的PHP重写CSS文件

时间:2016-02-20 22:59:58

标签: php

我有一个php文件,在htaccess中重命名为css文件。原因是因为我有一些样式和颜色会根据一些管理选项而改变。

无论如何,我试图允许访问者的浏览器缓存文件。这就是我所拥有的:

style.php:

header("Content-type: text/css; charset: UTF-8");

// Start normal CSS styles...

htaccess的:

RewriteRule ^assets/css/min/([a-zA-Z0-9\._-]+)/([a-zA-Z0-9\._-]+)/([a-zA-Z0-9\._-]+)\.css$ assets/css/min.php?style=$1&layout=$2&ver=$3 [L,QSA]

# Compress
AddOutputFilterByType DEFLATE text/css

# Cache for 1 week
<FilesMatch ".(css)$">
Header set Cache-Control "max-age=604800"
</FilesMatch>

<IfModule mod_expires.c>
    ExpiresActive on
    ExpiresByType text/css "access plus 1 week"

</IfModule>

在页面头部:

<link rel="stylesheet" href="http://example.com/assets/css/min/blue/flat/0.9.2.css">

每次加载新页面时,都会请求页面内容。这些是我收到的标题:

Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection: Keep-Alive
Content-Encoding: gzip
Content-Length: 13881
Content-Type: text/css; charset: UTF-8;charset=UTF-8
Date: Sat, 20 Feb 2016 22:49:17 GMT
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive: timeout=5, max=94
Pragma: no-cache
Server: Apache/2.4.16 (Unix) OpenSSL/1.0.1p PHP/5.6.12 mod_perl/2.0.8-dev Perl/v5.16.3
Vary: Accept-Encoding,User-Agent
X-Powered-By: PHP/5.6.12

1 个答案:

答案 0 :(得分:3)

您的mod_expires配置根据网络服务器感知的mimetype应用于文件。除非您在其他地方对Web服务器配置进行了一些重大手术,否则Web服务器不会将text / CSS mimetype与以.php结尾的文件相关联(如果确实如此,则需要进一步的黑客攻击才能使其处理PHP解析器)。 PHP脚本设置的标头与此过程无关。

虽然可以强制mod_expires将缓存标头添加到响应中,但您还必须使用mod_headers来删除 PHP设置的值;当浏览器收到多个冲突的缓存指令时,它将采用表示的最短的到期时间。

因此,要使内容可缓存,您应该直接从PHP脚本发出缓存信息。 E.g。

header('Cache-control: max-age=604800; private');

但基于访问时间的到期时间不是最佳解决方案。