无法使用htaccess缓存静态文件

时间:2017-09-24 13:06:11

标签: php apache .htaccess caching

我是新手,我正在尝试测试如何缓存文件,所以我创建了一个简单的php网页来测试我是否可以缓存css文件:

<!doctype html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1 id="heading">Test</h1>
</body>
</html>

我创建了一个htaccess文件,然后从here

添加了这些行
    # ----------------------------------------------------------------------
# | Expires headers                                                    |
# ----------------------------------------------------------------------

# Serve resources with far-future expires headers.
#
# (!) If you don't control versioning with filename-based
# cache busting, you should consider lowering the cache times
# to something like one week.
#
# https://httpd.apache.org/docs/current/mod/mod_expires.html

<IfModule mod_expires.c>

    ExpiresActive on
    ExpiresDefault                                      "access plus 1 month"

  # CSS

    ExpiresByType text/css                              "access plus 1 year"

</IfModule>

然后我尝试更改样式以检查它是否缓存但每次加载时样式更改这意味着没有缓存,然后我认为我是本地服务器配置所以我移动到一个和agian仍然是与this site测试标题相同 我得到了这个:

HTTP/1.1 200 OK
Server: nginx/1.12.1
Date: Sun, 24 Sep 2017 13:02:51 GMT
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
Cache-Control: max-age=0
Expires: Sun, 24 Sep 2017 13:02:51 GMT
Vary: Accept-Encoding,User-Agent
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff

修改

我发现mode_expires在localhost上没有活动,我启用了它但仍然面临问题

1 个答案:

答案 0 :(得分:1)

尝试添加此部分:

<IfModule mod_headers.c>
 <FilesMatch "\.(ico|jpe?g|png|gif|swf|css|gz)$">
 Header set Cache-Control "max-age=2592000, public"
 </FilesMatch>
 <FilesMatch "\.(js)$">
 Header set Cache-Control "max-age=2592000, private"
 </FilesMatch>
<filesMatch "\.(html|htm)$">
Header set Cache-Control "max-age=7200, public"
</filesMatch>
# Disable caching for scripts and other dynamic files
<FilesMatch "\.(pl|php|cgi|spl|scgi|fcgi)$">
Header unset Cache-Control
</FilesMatch>
</IfModule>