【问题标题】:Setting cache control on Apache 2.4在 Apache 2.4 上设置缓存控制
【发布时间】:2023-04-02 23:35:02
【问题描述】:

我的网站托管在 Apache 2.4 上 我尝试满足 Google Insights 的建议,但我不断收到此建议

利用浏览器缓存 在静态资源的 HTTP 标头中设置到期日期或最长期限会指示浏览器从本地磁盘而不是通过网络加载先前下载的资源。 将浏览器缓存用于以下可缓存资源: https://www.google-analytics.com/analytics.js(2 小时)

在我添加的 .htaccess 文件中

<IfModule mod_headers.c>
    # WEEK
    <FilesMatch "\.(jpg|jpeg|png|gif|swf)$">
        Header set Cache-Control "max-age=604800, public"
    </FilesMatch>

    # WEEK
    <FilesMatch "\.(js|css|swf)$">
        Header set Cache-Control "max-age=604800"
    </FilesMatch>
</IfModule>

但是,这根本没有帮助。在我的 index.php 中,我尝试设置

<?php
header( 'Cache-Control: max-age=604800' );
?>

没有结果。我的整个 .htaccess 文件是:

<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
</IfModule>

<IfModule mod_expires.c>
# Enable expirations
ExpiresActive On
# Default directive
ExpiresDefault "access plus 1 month"
# My favicon
ExpiresByType image/x-icon "access plus 1 year"
# Images
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
# CSS
ExpiresByType text/css "access plus 1 month"
# Javascript
ExpiresByType application/javascript "access plus 1 year"
</IfModule>
ErrorDocument 400 /400.php
ErrorDocument 401 /401.php
ErrorDocument 403 /403.php
ErrorDocument 404 /404.php
ErrorDocument 500 /500.php

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(.*)\.html$ $1.php?%{QUERY_STRING} [L]
</IfModule>

【问题讨论】:

    标签: php apache .htaccess caching


    【解决方案1】:

    您无法采取任何措施来影响异地资源。谷歌经常会标记你无法控制的事情。它也经常是 Google 资源。

    https://www.google-analytics.com/analytics.js
    

    这显然不在您的服务器上,因此您不能更改它的任何标题。不要太担心在 PageSpeed 上获得满分。只担心那些你可以控制的事情。

    【讨论】:

    • 我认为这个想法是在我这边设置 Cache-Control?好像我错了?附言我不担心,我的 SEO 是 :D
    • @Dimentica 您确实为自己设置了它。但仅适用于来自您的服务器的东西。您不能为其他网站或您的网站引用的资源设置它。 Cache-Control 是从服务器传递到客户端时附加到每个文件的标头。客户端从不向您的服务器请求analytics.js,因为主机是 Google。
    • 我现在明白了 :) 这就是人们试图以此欺骗 Google 的原因。谢谢!
    猜你喜欢
    • 2011-10-01
    • 1970-01-01
    • 2017-07-16
    • 1970-01-01
    • 2014-10-02
    • 2016-08-23
    • 2018-07-24
    • 2015-04-27
    • 2019-12-22
    相关资源
    最近更新 更多