All Products
Search
Document Center

Object Storage Service:Hotlink protection (Python SDK V2)

Last Updated:Mar 20, 2026

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:PutBucketReferer permission to set or delete hotlink protection configurations

  • The oss:GetBucketReferer permission to retrieve hotlink protection configurations

  • For 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

Set hotlink protection

put_bucket_referer(request: PutBucketRefererRequest, **kwargs) → PutBucketRefererResult

Request syntax:

result = client.put_bucket_referer(oss.PutBucketRefererRequest(
    bucket='<your-bucket-name>',
    referer_configuration=oss.RefererConfiguration(
        allow_empty_referer=True,          # bool — allow requests with no Referer header
        allow_truncate_query_string=False, # bool — strip query strings before matching
        truncate_path=False,               # bool — strip URL path before matching
        referer_list=oss.RefererList(
            referers=['https://example.com'],     # whitelist entries
        ),
        referer_blacklist=oss.RefererBlacklist(
            referers=['https://blocked.com'],     # blacklist entries
        ),
    ),
))

Parameters:

ParameterTypeRequiredDescription
bucketstrYesThe name of the bucket
referer_configurationRefererConfigurationYesThe hotlink protection configuration
allow_empty_refererboolNoWhether to allow requests without a Referer header. Default: True
allow_truncate_query_stringboolNoWhether to strip the query string from the Referer URL before matching. Default: False
truncate_pathboolNoWhether to strip the URL path from the Referer URL before matching. Default: False
referer_listRefererListNoWhitelist of allowed Referer values
referer_blacklistRefererBlacklistNoBlacklist of denied Referer values

For the complete parameter reference, see PutBucketRefererRequest and put_bucket_referer.

Get hotlink protection settings

get_bucket_referer(request: GetBucketRefererRequest, **kwargs) → GetBucketRefererResult

For the complete parameter reference, see GetBucketRefererRequest and get_bucket_referer.

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