【发布时间】:2018-10-27 18:22:21
【问题描述】:
我有一个网站,我在所有页面/图像和脚本上添加了过期标头,但我不知道如何将过期标头添加到外部脚本。
例如 Google Analytics - 它已将过期标头设置为 1 天。
Google 不是我的问题,来自外部网站的其他一些脚本才是真正的问题,它们根本没有过期标头。
【问题讨论】:
标签: http header http-headers
我有一个网站,我在所有页面/图像和脚本上添加了过期标头,但我不知道如何将过期标头添加到外部脚本。
例如 Google Analytics - 它已将过期标头设置为 1 天。
Google 不是我的问题,来自外部网站的其他一些脚本才是真正的问题,它们根本没有过期标头。
【问题讨论】:
标签: http header http-headers
您只能在响应发送到您自己的服务器的请求时添加标头字段。如果请求发送到另一台服务器,比如 Google 的服务器,那么响应请求的是 Google 的服务器。
因此,解决您的问题的唯一方法是将外部资源托管在您自己的服务器上。但这只有在资源是静态的、不会因请求而变化且不依赖于其他事物的情况下才有可能。
【讨论】:
唯一的方法是创建从外部站点下载内容然后添加所需标题的脚本。
<script type="text/javascript" src="http://external.example.com/foo.js"></script>
到
<script type="text/javascript" src="external.php?url=http://external.example.com/foo.js"></script>
external.php 类似于
<?php
header("Expire-stuff: something");
echo file_get_contents($_GET['url']);
当然这有安全漏洞,所以我建议使用诸如 external.php?file=foo.js 之类的标识符字符串,然后使用
$files = array('foo.js' => 'http://external/...');
if(isset($files[$_GET['file']]))
{
echo file_get_contents($files[$_GET['file']]);
}
file_get_contents() 当然会占用你的一些带宽,所以建议也缓存结果。
【讨论】:
这是不可能的。
不推荐(并不总是可能):如果是静态内容,请使用脚本预取它并设置您自己的标题。
【讨论】:
您可以使用 PHP 动态加载外部页面,因此您可以在输出原始数据之前发送标头。这不是一个理想的解决方案,但如果你真的需要,你可能想要使用它。
<?php
header('expire-header');
echo file_get_contents('http://www.extern.al/website/url');
【讨论】:
我制作了该代码的一个版本,可让您为每个脚本指定不同的过期日期:
<?php
$files = array(
'ga.js' => 'https://ssl.google-analytics.com/ga.js',
'bsa.js' => 'https://s3.buysellads.com/ac/bsa.js',
'pro.js' => 'https://s3.buysellads.com/ac/pro.js'
);
if(isset($files[$_GET['file']])) {
if ($files[$_GET['file']] == 'ga.js'){
header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + ((60 * 60) * 48))); // 2 days for GA
} else {
header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + (60 * 60))); // Default set to 1 hour
}
echo file_get_contents($files[$_GET['file']]);
}
?>
更多信息:https://www.catswhocode.com/blog/php-how-to-add-expire-headers-for-external-scripts
【讨论】:
不要对这些页面测试失去理智...其中一些建议可能有用,而其中一些建议您无能为力。对自己的文件做任何可以做的事情,不要介意外部文件。
【讨论】:
你不能。
尝试向托管文件的人发送电子邮件,并尝试让他们对其应用 expires-headers。
【讨论】:
以下内容可能对您有用。
ExpiresActive On
ExpiresDefault "access plus 1 seconds"
ExpiresByType image/x-icon "access plus 2692000 seconds"
ExpiresByType image/jpeg "access plus 2692000 seconds"
ExpiresByType image/png "access plus 2692000 seconds"
ExpiresByType image/gif "access plus 2692000 seconds"
ExpiresByType application/x-shockwave-flash "access plus 2692000 seconds"
ExpiresByType text/css "access plus 2692000 seconds"
ExpiresByType text/javascript "access plus 2692000 seconds"
ExpiresByType application/x-javascript "access plus 2692000 seconds"
ExpiresByType text/html "access plus 600 seconds"
ExpiresByType application/xhtml+xml "access plus 600 seconds"
【讨论】:
您可以添加一个查询字符串参数来欺骗浏览器,使其认为它正在请求不同的资源。例如,如果您希望浏览器从不缓存 CSS,您可以在 URL 的末尾添加一个问号,后跟一个随机数。这通常有效,但可以通过托管文件的服务器使其无效。试试看。
【讨论】: