2009-09-17 20 views
18

我有一個網站,我在所有頁面/圖像和腳本上添加了過期標題,但我不知道如何將過期標題添加到外部腳本。如何爲不在服務器上的腳本添加過期頭文件?

例如Google Analytics(分析) - 它已將過期的標題設置爲1天。

谷歌是我的問題,其他一些來自外部網站的腳本是真正的問題,它們根本沒有過期的頭文件。

回答

19

您只能添加標題字段作爲對發送到您自己的服務器的請求的響應。如果請求發送到另一臺服務器,比如Google的服務器,那麼這個服務器就是Google的服務器,它會迴應請求。

因此,解決您的問題的唯一辦法是在您自己的服務器上託管外部資源。但是這隻有在資源是靜態的時候纔有可能,不要求從請求變爲請求而不依賴於其他事情。

0

你不能。

嘗試通過電子郵件發送承載文件的人並嘗試讓他們將過期標題應用於該文件。

2

那是不可能的。

不推薦(並不總是可能的):如果它的靜態內容,使用腳本預取它並設置您自己的標題。

2

您可以使用PHP動態加載外部頁面,因此您可以在輸出原始數據之前發送標題。這不是一個理想的解決方案,但如果你真的需要你可能想使用它。

<?php 
header('expire-header'); 

echo file_get_contents('http://www.extern.al/website/url'); 
+0

這將不適用於所有外部腳本,我嘗試過一個magento站點,但無法正常工作。 – prajosh

19

唯一的方法是創建腳本,從外部站點下載內容,然後添加需要的標題。

<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?文件= foo.js然後使用

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

file_get_contents()當然會佔用一些帶寬,因此建議緩存結果。

+0

有趣!這是否有任何速度影響? – v3nt

-9

您可能可以添加查詢字符串參數來欺騙瀏覽器,使其認爲它正在請求其他資源。例如,如果您希望瀏覽器永遠不緩存CSS,則可以在URL的末尾添加一個問號,隨後是一個隨機數。這通常可以工作,但可以使託管該文件的服務器無法工作。試試看看。

+0

需要遵循標準而不是廉價的技巧。 –

0

下面的內容可能對您有用。

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" 

+1

沒有。你只能將它添加到你自己的js文件中。您不能將此添加到外部js文件。 –

0

我做了一個版本的代碼,讓您爲每個腳本指定不同的到期日期:

<?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

相關問題