圖片、視頻、下載檔案等靜態資源被外站直接引用(盜鏈),會消耗源站頻寬並影響使用者體驗。Nginx 提供內建 valid_referers 指令與第三方 ngx_http_accesskey_module 兩種防盜鏈機制,本文詳細說明配置方法與適用場景。
location ~* \.(gif|jpg|jpeg|png|bmp|swf|flv|mp4|webm)$ {
valid_referers none blocked example.com www.example.com *.example.com;
if ($invalid_referer) {
rewrite ^/ https://example.com/403.html permanent;
# return 403; # 或直接回傳 403/404
}
}
| 指令/參數 | 說明 |
|---|---|
~* \.(gif|jpg|...)$ | 不區分大小寫匹配需保護的副檔名 |
valid_referers | 定義合法來源:none(無 Referer,如直接輸入網址)、blocked(防火牆/代理過濾 Referer)、域名列表(支援通配符) |
$invalid_referer | 內建變數,Referer 不在白名單中時為 1 |
rewrite ... permanent | 301 導向自定義錯誤頁,避免直接 403 影響 SEO |
需編譯 Nginx 時加入 --add-module=path/to/ngx_http_accesskey_module。
https://cdn.example.com/download/file.zip?key=hmac_sha256(ip+timestamp+secret)key 是否合法且未過期。location /download/ {
accesskey on;
accesskey_hashmethod md5;
accesskey_arg "key";
accesskey_signature "mypass$remote_addr";
# 簽名 = md5("mypass" + $remote_addr + $uri + $arg_timestamp)
}
| 場景 | 推薦方案 |
|---|---|
| 一般圖片/靜態資源防盜鏈、SEO 友善 | 方案一 |
| 付費下載、私有視頻、高價值資源防盜鏈 | 方案二 |
| CDN 邊緣節點配合 | 方案二(CDN 多支援 Edge 機能驗證) |
結合 referer 白名單(允許搜尋引擎爬蟲)與 accesskey 加密連結,可構建分層防盜鏈體系。