Use the OSS SDK for Python V2 to configure Referer-based access control for a bucket — set a whitelist, a blacklist, and control whether requests with empty Referer headers are allowed. This prevents unauthorized sites from embedding your OSS resources and reduces unnecessary egress costs.
Prerequisites
Before you begin, ensure that you have:
Familiarity with hotlink protection concepts. See Hotlink protection
The
oss:PutBucketRefererpermission to set or delete hotlink protection configurationsThe
oss:GetBucketRefererpermission to retrieve hotlink protection configurationsFor custom permission setup, see Grant custom permissions to a RAM user
The examples in this topic use the China (Hangzhou) region (cn-hangzhou) with the public endpoint. To access OSS from another Alibaba Cloud service in the same region, use the internal endpoint instead. See OSS regions and endpoints.Method definitions
Examples
Both examples load credentials from environment variables and accept --region, --bucket, and an optional --endpoint as command-line arguments.
Set hotlink protection
The following example sets a whitelist, a blacklist, and enables empty Referer requests.
import argparse
import alibabacloud_oss_v2 as oss
parser = argparse.ArgumentParser(description="put bucket referer sample")
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
def main():
args = parser.parse_args()
# Load credentials from environment variables
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
cfg.region = args.region
if args.endpoint is not None:
cfg.endpoint = args.endpoint
client = oss.Client(cfg)
result = client.put_bucket_referer(oss.PutBucketRefererRequest(
bucket=args.bucket,
referer_configuration=oss.RefererConfiguration(
allow_empty_referer=True, # Allow requests without a Referer header
allow_truncate_query_string=False, # Do not strip query strings before matching
truncate_path=False, # Do not strip URL paths before matching
referer_list=oss.RefererList(
referers=['http://www.aliyun.com', 'https://www.aliyun.com'],
),
referer_blacklist=oss.RefererBlacklist(
referers=['http://www.refuse.com', 'http://www.refuse1.com'],
),
),
))
print(f'status code: {result.status_code},'
f' request id: {result.request_id}')
if __name__ == "__main__":
main()For the complete sample, see put_bucket_referer.py.
Get hotlink protection settings
The following example retrieves the current hotlink protection configuration and prints each field.
import argparse
import alibabacloud_oss_v2 as oss
parser = argparse.ArgumentParser(description="get bucket referer sample")
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
def main():
args = parser.parse_args()
# Load credentials from environment variables
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
cfg.region = args.region
if args.endpoint is not None:
cfg.endpoint = args.endpoint
client = oss.Client(cfg)
result = client.get_bucket_referer(oss.GetBucketRefererRequest(
bucket=args.bucket,
))
print(f'status code: {result.status_code},'
f' request id: {result.request_id},'
f' allow empty referer: {getattr(result.referer_configuration, "allow_empty_referer", "Not set")},'
f' allow truncate query string: {getattr(result.referer_configuration, "allow_truncate_query_string", "Not set")},'
f' truncate path: {getattr(result.referer_configuration, "truncate_path", "Not set")},'
f' referer list: {getattr(result.referer_configuration, "referer_list", "Not set")},'
f' referer blacklist: {getattr(result.referer_configuration, "referer_blacklist", "Not set")}')
if __name__ == "__main__":
main()For the complete sample, see get_bucket_referer.py.
References
For information about how to troubleshoot common errors that occur when you configure hotlink protection, see Hotlink protection error reference.
To configure hotlink protection using the OSS console or other methods, see Hotlink protection.
For API-level details, see PutBucketRefererResult and GetBucketRefererResult.