All Products
Search
Document Center

Object Storage Service:Hotlink protection (Python SDK V2)

Last Updated:Aug 01, 2025

You can use the Alibaba Cloud OSS SDK for Python to configure access rules based on the Referer request header, such as setting a Referer whitelist, a Referer blacklist, and specifying whether to allow empty Referer headers. These configurations allow you to block specific Referer headers from accessing your OSS files, prevent unauthorized use of your resources, and avoid unnecessary traffic costs.

Prerequisites

  • Before you configure hotlink protection, make sure that you understand this feature. For more information, see Hotlink protection.

  • The sample code in this topic uses the China (Hangzhou) region (ID: cn-hangzhou) as an example. By default, the public endpoint is used. If you want to access OSS from other Alibaba Cloud services in the same region, use the internal endpoint. For more information about OSS regions and their corresponding endpoints, see OSS regions and endpoints.

  • To set or delete hotlink protection configurations, you must have the oss:PutBucketReferer permission. To retrieve hotlink protection configurations, you must have the oss:GetBucketReferer permission. For more information, see Grant custom permissions to a RAM user.

Method definitions

Set hotlink protection

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

Obtain hotlink protection settings

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

Request parameters

Parameter

Type

Description

request

PutBucketRefererRequest

The request parameters. For more information, see PutBucketRefererRequest

GetBucketRefererRequest

The request parameters. For more information, see GetBucketRefererRequest

Return values

Type

Description

PutBucketRefererResult

The return value. For more information, see PutBucketRefererResult

GetBucketRefererResult

The return value. For more information, see GetBucketRefererResult

For the complete definition of the method for setting hotlink protection, see put_bucket_referer.

For the complete definition of the method for retrieving hotlink protection settings, see get_bucket_referer.

Examples

Set hotlink protection

You can use the following code to set hotlink protection.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser and describe the purpose of the script: configure hotlink protection for a bucket.
parser = argparse.ArgumentParser(description="put bucket referer sample")

# Define command-line arguments, including the required region, bucket name, and optional endpoint.
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():
    # Parse command-line arguments to obtain user-entered values.
    args = parser.parse_args()

    # Load access credential information from environment variables for identity verification.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Create a configuration object using the default SDK configurations and set the authentication provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Set the region property of the configuration object based on the command-line arguments provided by the user.
    cfg.region = args.region

    # If a custom endpoint is provided, update the endpoint property in the configuration object.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding configurations to initialize the OSS client for interacting with OSS.
    client = oss.Client(cfg)

    # Send a request to set the hotlink protection configuration for the specified bucket.
    result = client.put_bucket_referer(oss.PutBucketRefererRequest(
            bucket=args.bucket,  # The bucket name.
            referer_configuration=oss.RefererConfiguration(
                allow_empty_referer=True,  # Specifies whether to allow empty Referer headers. Default value: True.
                allow_truncate_query_string=False,  # Specifies whether to truncate the query string. Default value: False.
                truncate_path=False,  # Specifies whether to truncate the path. Default value: False.
                referer_list=oss.RefererList(
                    referers=['http://www.aliyun.com', 'https://www.aliyun.com'],  # The list of allowed Referer headers.
                ),
                referer_blacklist=oss.RefererBlacklist(
                    referers=['http://www.refuse.com', 'http://www.refuse1.com'],  # The blacklist of denied Referer headers.
                ),
            ),
    ))

    # Print the status code and request ID of the operation result to confirm the request status.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          )

# When this script is directly executed, call the main function to start processing the logic.
if __name__ == "__main__":
    main()  # The entry point of the script, from which the program flow starts.

Obtain hotlink protection settings

You can use the following code to retrieve hotlink protection configurations.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser and describe the purpose of the script: obtain the hotlink protection configuration of a bucket.
parser = argparse.ArgumentParser(description="get bucket referer sample")

# Define command-line arguments, including the required region, bucket name, and optional endpoint.
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():
    # Parse command-line arguments to obtain user-entered values.
    args = parser.parse_args()

    # Load access credential information from environment variables for identity verification.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Create a configuration object using the default SDK configurations and set the authentication provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    
    # Set the region property of the configuration object based on the command-line arguments provided by the user.
    cfg.region = args.region

    # If a custom endpoint is provided, update the endpoint property in the configuration object.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding configurations to initialize the OSS client for interacting with OSS.
    client = oss.Client(cfg)

    # Send a request to obtain the hotlink protection configuration for the specified bucket.
    result = client.get_bucket_referer(oss.GetBucketRefererRequest(
            bucket=args.bucket,  # The bucket name.
    ))

    # Print the status code, request ID, and hotlink protection configuration details of the operation result to confirm the request status and configuration details.
    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")},'
          )

# When this script is directly executed, call the main function to start processing the logic.
if __name__ == "__main__":
    main()  # The entry point of the script, from which the program flow starts.

References

  • For information about how to troubleshoot common errors that occur when you configure hotlink protection, see 33-REFERER.

  • For the complete sample code for setting hotlink protection, see put_bucket_referer.py.

  • For the complete sample code for retrieving hotlink protection configurations, see get_bucket_referer.py.