All Products
Search
Document Center

Object Storage Service:Configure hotlink protection using Python SDK V2 to prevent other websites from referencing OSS files

Last Updated:Mar 13, 2025

You can use the Alibaba Cloud OSS Python SDK to configure access rules based on the request header Referer, including setting a whitelist Referer, a blacklist Referer, and whether to allow an empty Referer. With these configurations, you can block specific Referer from accessing your OSS files to prevent other websites from misusing your resources, thereby avoiding unnecessary traffic cost increases.

Precautions

  • Before configuring hotlink protection, ensure that you are familiar with this feature. For more information, see hotlink protection.

  • This topic includes sample code that uses the China (Hangzhou) region ID cn-hangzhou as an example. By default, the public endpoint is utilized. To access OSS from other Alibaba Cloud products within the same region, you should use the internal endpoint. For more information about the correlation between OSS-supported regions and their endpoints, see OSS regions and endpoints.

  • To configure or remove hotlink protection, you must have the oss:PutBucketReferer permission. To use hotlink protection, you must have the oss:GetBucketReferer permission. For detailed instructions, see grant custom policy to RAM users.

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 name

Type

Value

request

PutBucketRefererRequest

Set request parameters. For more information, see PutBucketRefererRequest

GetBucketRefererRequest

Set request parameters. For more information, see GetBucketRefererRequest

Return values

Type

Value

PutBucketRefererResult

Return value. For more information, see PutBucketRefererResult

GetBucketRefererResult

Return value. For more information, see GetBucketRefererResult

For the complete method definition to set hotlink protection, see put_bucket_referer.

For the complete method definition to obtain hotlink protection settings, see get_bucket_referer.

Example code

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 script's purpose: set the hotlink protection configuration 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 input values
    args = parser.parse_args()

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

    # Create a configuration object using the SDK default configuration 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 user-provided command line arguments
    cfg.region = args.region

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

    # Use the preceding configuration to initialize the OSS client and prepare for interaction 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,  # Bucket name
            referer_configuration=oss.RefererConfiguration(
                allow_empty_referer=True,  # Whether to allow an empty Referer, the default is True
                allow_truncate_query_string=False,  # Whether to allow truncating the query string, the default is False
                truncate_path=False,  # Whether to truncate the path, the default is False
                referer_list=oss.RefererList(
                    referers=['http://www.aliyun.com', 'https://www.aliyun.com'],  # Allowed Referer list
                ),
                referer_blacklist=oss.RefererBlacklist(
                    referers=['http://www.refuse.com', 'http://www.refuse1.com'],  # Rejected Referer blacklist
                ),
            ),
    ))

    # 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},'
          )

# Call the main function to start the processing logic when the script is directly run
if __name__ == "__main__":
    main()  # Script entry point, control program flow starts here

Obtain hotlink protection settings

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

import argparse
import alibabacloud_oss_v2 as oss

# Create a command line argument parser and describe the script's purpose: obtain the hotlink protection configuration for 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 input values
    args = parser.parse_args()

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

    # Create a configuration object using the SDK default configuration 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 user-provided command line arguments
    cfg.region = args.region

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

    # Use the preceding configuration to initialize the OSS client and prepare for interaction 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,  # 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")},'
          )

# Call the main function to start the processing logic when the script is directly run
if __name__ == "__main__":
    main()  # Script entry point, control program flow starts here

References

  • For assistance with common errors associated with hotlink protection, see 33-REFERER.

  • For the complete sample code to set hotlink protection, see put_bucket_referer.py.

  • For the complete sample code to retrieve hotlink protection settings, see get_bucket_referer.py.