本文介绍如何使用防盗链。

为了防止您在OSS上的数据被其他人盗链而产生额外费用,您可以设置防盗链功能,包括以下参数:
  • Referer白名单。仅允许指定的域名访问OSS资源。
  • 是否允许空Referer。如果不允许空Referer,则只有HTTP或HTTPS header中包含Referer字段的请求才能访问OSS资源。

更多关于防盗链的介绍,请参见开发指南中的设置防盗链

设置Referer白名单

通过putBucketReferer设置Referer白名单。

let OSS = require('ali-oss')

let client = new OSS({
  region: '<Your region>'
  accessKeyId: '<Your AccessKeyId>',
  accessKeySecret: '<Your AccessKeySecret>',
  bucket: '<Your bucket name>'
});

async function putBucketReferer () {
  try {
  let result = await client.putBucketReferer('bucket-name', true, [
    'example.com',
    '*.example.com'
  ]);
  console.log(result);
  } catch (e) {
    console.log(e);
  }
 }

putBucketReferer();

查看Referer白名单

通过getBucketReferer查看Referer白名单。

let OSS = require('ali-oss')

let client = new OSS({
  region: '<Your region>'
  accessKeyId: '<Your AccessKeyId>',
  accessKeySecret: '<Your AccessKeySecret>',
  bucket: '<Your bucket name>'
});

async function getBucketReferer () {
  try {
    let result = await client.getBucketReferer('bucket-name');
    console.log(result);
  } catch (e) {
    console.log(e);
  }
}

getBucketReferer();

清空Referer白名单

通过deleteBucketReferer清空Referer白名单。

let OSS = require('ali-oss')
let client = new OSS({
  region: '<Your region>'
  accessKeyId: '<Your AccessKeyId>',
  accessKeySecret: '<Your AccessKeySecret>',
  bucket: '<Your bucket name>'
});

async function deleteBucketReferer () {
  try {
    let result = await client.deleteBucketReferer('bucket-name');
    console.log(result);
  } catch (e) {
    console.log(e);
  }
}

deleteBucketReferer();