熱鏈保護
更新時間 2024-07-19 16:09:18
最近更新時間: 2024-07-19 16:09:18
分享文章
本文介紹如何使用邊緣函數阻止其他網站盜鏈您的內容。
阻止其他網站盜鏈您的內容。
示例代碼
const HOMEPAGE_URL = "//daliqc.cn/"
const PROTECTED_TYPE = "image/"
async function handleRequest(request) {
// Fetch the original request
const response = await fetch(request)
// If it's an image, engage hotlink protection based on the
// Referer header.
const referer = request.headers.get("Referer")
const contentType = response.headers.get("Content-Type") || ""
if (referer && contentType.startsWith(PROTECTED_TYPE)) {
// If the hostnames don't match, it's a hotlink
if (new URL(referer).hostname !== new URL(request.url).hostname) {
// Redirect the user to your website
return Response.redirect(HOMEPAGE_URL, 302)
}
}
// Everything is fine, return the response normally.
return response
}
addEventListener("fetch", event => {
event.respondWith(handleRequest(event.request))
})
示例預覽
當一個請求到達時,首先檢查其Content-Type是否是圖像類型。
如果是圖像類型,再檢查 Referer頭部是否指向當前域名。
如果 Referer頭部指向的域名與當前域名不一致,則重定向到主頁。