HTTP Referer(拼寫錯誤保留至今)是請求標頭之一,告知伺服器請求來源頁面。雖被廣泛用於防盜鏈、統計分析,但其可被客戶端輕易偽造,不可用於安全驗證。本文系統梳理原理、偽造方法、防盜鏈配置與最佳實踐。
瀏覽器發起請求時自動附帶 Referer 標頭,格式如:
Referer: https://example.com/page.html
伺服器可據此統計流量來源、實作防盜鏈。但 RFC 7231 規定:從 HTTPS 頁面跳轉至 HTTP 時,瀏覽器不得發送 Referer,這是為保護敏感資訊不洩露至非加密連線。
在 about:config 中調整:
network.http.sendRefererHeader:0=不發送、1=僅點擊連結、2=始終發送(預設)network.http.sendSecureXSiteReferrer:跨站 HTTPS→HTTPS 是否發送(預設 true)$ch = curl_init('https://target.com/resource.jpg');
curl_setopt($ch, CURLOPT_REFERER, 'https://allowed.com/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$img = curl_exec($ch);
$fp = fsockopen('target.com', 80);
$out = "GET /resource.jpg HTTP/1.1\r\n";
$out .= "Host: target.com\r\n";
$out .= "Referer: https://allowed.com/\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
瀏覽器安全策略禁止 JS 修改 Referer,xmlHttp.setRequestHeader('Referer', ...) 會被忽略或拋出錯誤。
Privoxy 規則範例:
{+hide-referrer{forge}}
.album.sina.com.cn
forge 以目標 URL 偽造 Referer,block 則完全移除。
<Directory /var/www/images>
SetEnvIfNoCase Referer "^https?://www\.yourdomain\.com/" local_ref
SetEnvIf Referer "^$" local_ref # 允許直接訪問(無 Referer)
<FilesMatch "\.(gif|jpg|png|webp)$">
Order Deny,Allow
Deny from all
Allow from env=local_ref
</FilesMatch>
</Directory>
location ~* \.(gif|jpg|png|webp)$ {
valid_referers none blocked server_names
*.yourdomain.com
~\.google\. ~\.bing\. ~\.yahoo\.;
if ($invalid_referer) {
return 403;
# 或重導至預設圖片:rewrite ^/ /static/nohotlink.png last;
}
}
永遠不要將 Referer 用於身份驗證、授權檢查、CSRF 防禦等安全關鍵邏輯。
正確替代方案:
Referer 適合「統計分析、輔助防盜鏈、用戶行為洞察」,不適合「任何安全決策」。現代 Web 應採用零信任原則,所有敏感操作均需強加密驗證機制保護。