如何为不在我的服务器上的脚本添加过期标头?

Dan*_*Tdr 20 header http http-headers

我有一个网站,我在所有页面/图像和脚本上添加了过期标题,但我不知道如何将expire标题添加到外部脚本.

例如Google Analytics(分析) - 它将过期标头设置为1天.

谷歌不是我的问题,外部网站的一些其他脚本是真正的问题,他们根本没有过期的标题.

Gum*_*mbo 21

您只能在响应转发到您自己的服务器的请求时添加标头字段.如果请求转到另一台服务器,比如Google的服务器,那么它的Google服务器会回复请求.

因此,解决您问题的唯一方法是在您自己的服务器上托管外部资源.但这只有在资源是静态的情况下才有可能,不会从请求变为请求而不依赖于其他事情.


ras*_*spi 20

唯一的方法是创建脚本,从外部站点下载内容,然后添加所需的标题.

<script type="text/javascript" src="http://external.example.com/foo.js"></script>
Run Code Online (Sandbox Code Playgroud)

<script type="text/javascript" src="external.php?url=http://external.example.com/foo.js"></script>
Run Code Online (Sandbox Code Playgroud)

而external.php就是这样的

<?php
header("Expire-stuff: something");
echo file_get_contents($_GET['url']);
Run Code Online (Sandbox Code Playgroud)

当然这有安全漏洞,所以我建议使用像external.php?file = foo.js这样的标识符字符串然后使用

$files = array('foo.js' => 'http://external/...');
if(isset($files[$_GET['file']]))
{
  echo file_get_contents($files[$_GET['file']]);
}
Run Code Online (Sandbox Code Playgroud)

file_get_contents()当然会占用你的一些带宽,因此建议也要缓存结果.