[TOC]

为什么使用b2

有很多人使用github,gitee等开源库做图床,也有很多现成的图床软件支持,但是我为什么不用呢?

  • 比如github 的tos是不支持做完纯储存的,有封号危险
  • github 的一个库有1G的限制,如果超过1G,回触发人工审核,因此可能会被发现是储存库
  • b2的容量大,10个G
  • 超过10个G之后的流量也很便宜(白嫖必然不用)
  • b2是cloudflare的宽带联盟成员,使用cf访问b2是免费的
  • dropshare,cloudmounter,cyberduck等软件的良好支持

    环境准备

  • 一个email
  • 一个 gv号码
  • cloudflare
  • dropshare app

B2设置

点击 backblaze 注册地址 注册,注册之后使用gv号验证,邮箱也验证一下。

  1. 创建一个Bucket:

这个bucketname 一定要起一个特别的,防止被猜到刷流量

  1. 创建一个App keys

    目的是为了让 Dropshare 这样的第三方软件接入使用 backblaze,用于上传图片。

    点击 Add a New Application Key,选择好要操作的bucket,生产即可。

    创建成功之后保存这个信息,因为关闭之后就不会再显示了。

  2. 获取bucket的信息
    回到刚才创建好的bucket,上传一个图片,点击这个图片可以看到这个图片的信息。

    我们最关心的地方是Friendly URL这个字段,比如:

    https://f002.backblazeb2.com/file/bucketname/filename.suffix
    

    记住 https://f002.backblazeb2.com/ 这个url,后面要用。

cloudflare 设置1

  1. 创建一个cname 类型的dns记录,指向之前的域名(本例中为f002.backblazeb2.com)

Dropshare 设置

连接到B2,如下图所示 :


bucket id 在Buckets列表内有.
这样上传图片到b2之后,会自动生成我们图床域名的url。贴心啊!

cloudflare 设置2:cloudflare worker

目的:我们的目标是要省去/file/桶名称/ 那部分,使链接更友好,也防止被猜到浪费流量.

'use strict';
const b2Domain = 'img.domain.com'; // 你的图床的域名
const b2Bucket = 'bucket-name'; // bucket名字
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;
}

此时我们 把图床的域名绑定到这个worker,请求这个图床域名的时候,先去这个worker里处理一下。

点击域名部分的 Workers->http路由->添加路由:

缓存设置

点击域名主页,规则设置,点击创建页面规则,输入你的图床域名,注意后面要有一个星号,即:你的图床域名/* ,因为这个页面规则是按照你的url匹配的,所以需要一个通配符来匹配(你也可以自行设置).

cloudflare设置2:防盗链设置

域名部分的防火墙->防火墙规则->创建防火墙规则,规则如下:

如果 请求头(referer)里面没有包含有我博客的域名(白名单域名),并且(and),完整请求(url full)里包含有我的图床域名,那么就阻止这个请求.

参考链接

  1. https://wlnxing.com/archives/49.html
  2. https://blog.meow.page/archives/free-personal-image-hosting-with-backblaze-b2-and-cloudflare-workers/
  3. cloudflare.com/zh-cn/bandwidth-alliance/