-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHot-Link Protection
More file actions
22 lines (22 loc) · 840 Bytes
/
Hot-Link Protection
File metadata and controls
22 lines (22 loc) · 840 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const HOMEPAGE_URL = 'https://tutorial.cloudflareworkers.com/'
const PROTECTED_TYPE = 'images/'
async function handleRequest(request) {
// Fetch the original request
let response = await fetch(request)
// If it's an image, engage hotlink protection based on the
// Referer header.
let referer = request.headers.get('Referer')
let 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(url, 302)
}
}
// Everything is fine, return the response normally.
return response
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})