Cloudflare Workers 允许你在 Cloudflare 全球网络中的边界服务器运行 JavaScript 代码, 使开发者可以部署 serverless(无需服务器) 的应用程序,并且自动缩放. 对于部署的 worker , 以下是我们想要达到的目标:
去除Backblaze B2URL 中的 /file/<bucket-name> 部分
加上基本的 CORS 请求头,以便允许图片嵌入到网站中
为图片优化缓存 (浏览器的缓存, 以及 CDN 边界服务器上的缓存)
在 Cloudflare 你的域名处, 创建一个新的 worker 脚本.
使用前,注意修改 b2Domain 和 b2Bucket 这两个变量的值.
b2Domain,是你域名。
b2Bucket,是你的 bucket 存储桶的名字。
'use strict';
const b2Domain = 'img.domain.com'; // configure this as per instructions above
const b2Bucket = 'bucket-name'; // configure this as per instructions above
const b2UrlPath = `/file/${b2Bucket}/`;
addEventListener('fetch', event => {
return event.respondWith(fileReq(event));
});
// define the file extensions we wish to add basic access control headers to
const corsFileTypes = ['png', 'jpg', 'gif', 'jpeg', 'webp'];
// backblaze returns some additional headers that are useful for debugging, but unnecessary in production. We can remove these to save some size
const removeHeaders = [
'x-bz-content-sha1',
'x-bz-file-id',
'x-bz-file-name',
'x-bz-info-src_last_modified_millis',
'X-Bz-Upload-Timestamp',
'Expires'
];
const expiration = 31536000; // override browser cache for images - 1 year
// define a function we can re-use to fix headers
const fixHeaders = function(url, status, headers){
let newHdrs = new Headers(headers);
// add basic cors headers for images
if(corsFileTypes.includes(url.pathname.split('.').pop())){
newHdrs.set('Access-Control-Allow-Origin', '*');
}
// override browser cache for files when 200
if(status === 200){
newHdrs.set('Cache-Control', "public, max-age=" + expiration);
}else{
// only cache other things for 5 minutes
newHdrs.set('Cache-Control', 'public, max-age=300');
}
// set ETag for efficient caching where possible
const ETag = newHdrs.get('x-bz-content-sha1') || newHdrs.get('x-bz-info-src_last_modified_millis') || newHdrs.get('x-bz-file-id');
if(ETag){
newHdrs.set('ETag', ETag);
}
// remove unnecessary headers
removeHeaders.forEach(header => {
newHdrs.delete(header);
});
return newHdrs;
};
async function fileReq(event){
const cache = caches.default; // Cloudflare edge caching
const url = new URL(event.request.url);
if(url.host === b2Domain && !url.pathname.startsWith(b2UrlPath)){
url.pathname = b2UrlPath + url.pathname;
}
let response = await cache.match(url); // try to find match for this request in the edge cache
if(response){
// use cache found on Cloudflare edge. Set X-Worker-Cache header for helpful debug
let newHdrs = fixHeaders(url, response.status, response.headers);
newHdrs.set('X-Worker-Cache', "true");
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: newHdrs
});
}
// no cache, fetch image, apply Cloudflare lossless compression
response = await fetch(url, {cf: {polish: "lossless"}});
let newHdrs = fixHeaders(url, response.status, response.headers);
if(response.status === 200){
response = new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: newHdrs
});
}else{
response = new Response('File not found!', { status: 404 })
}
event.waitUntil(cache.put(url, response.clone()));
return response;
}
进入 workers 功能,点击 Launch Editor ,进入编辑器,将以上代码拷贝到编辑器中,然后保存 worker。
使用了这个 worker 后, 你可以从 URL 中去掉 /file/<bucket-name>/ 部分, 使得生成的 URL 是这样的形式 https://subdomain.domain.com/test.txt, 而不是 https://subdomain.domain.com/file/<bucket-name>/test.txt.
最后,添加一条 worker 的路由规则,使访问 subdomain.domain.com/*时,请求先由 worker 来处理。
本文共 230 个字数,平均阅读时长 ≈ 1分钟
评论 (0)