阻止其他网站盗链您的内容。
示例代码
const HOMEPAGE_URL = "https://ctyun.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头部指向的域名与当前域名不一致,则重定向到主页。