All Products
Search
Document Center

Object Storage Service:Configure static website hosting (mirroring-based back-to-origin) by using OSS SDK for Python

Last Updated:Nov 01, 2024

You can enable static website hosting for buckets and configure mirroring-based back-to-origin rules. After you host a static website on a bucket, you can access the bucket to visit the website. You are automatically redirected to the specified index page or error page. After mirroring-based back-to-origin rules are configured and take effect, you can use mirroring-based back-to-origin to seamlessly migrate data to Object Storage Service (OSS).

Usage notes

  • In this topic, the public endpoint of the China (Hangzhou) region is used. If you want to access OSS from other Alibaba Cloud services in the same region as OSS, use an internal endpoint. For more information about OSS regions and endpoints, see Regions, endpoints and open ports.

  • In this topic, access credentials are obtained from environment variables. For more information about how to configure access credentials, see Configure access credentials.

  • In this topic, an OSSClient instance is created by using an OSS endpoint. If you want to create an OSSClient instance by using custom domain names or Security Token Service (STS), see Initialization.

  • To configure static website hosting or mirroring-based back-to-origin, you must have the oss:PutBucketWebsite permission. To query static website hosting configurations or mirroring-based back-to-origin rules, you must have the oss:GetBucketWebsite permission. To delete static website hosting configurations or mirroring-based back-to-origin rules, you must have the oss:DeleteBucketWebsite permission. For more information, see Common examples of RAM policies.

Static website hosting

  • Configure static website hosting

    The following sample code provides an example on how to configure static website hosting:

    #-*-coding:utf-8-*-
    import oss2
    from oss2.models import BucketWebsite
    from oss2.credentials import EnvironmentVariableCredentialsProvider
    
    # Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    
    # Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    # Specify the region in which the bucket is located. Example: cn-hangzhou This parameter is required if you use the V4 signature algorithm.
    region = "cn-hangzhou"
    
    # Replace examplebucket with the name of the bucket. 
    bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)
    
    # Enable static website hosting, set the default homepage to index.html, and then set the default 404 page to error.html. 
    bucket.put_bucket_website(BucketWebsite('index.html', 'error.html'))           
  • Query static website hosting configurations

    The following sample code provides an example on how to query static website hosting configurations:

    #-*-coding:utf-8-*-
    import oss2
    from oss2.models import BucketWebsite
    from oss2.credentials import EnvironmentVariableCredentialsProvider
    
    # Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    
    # Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    # Specify the region in which the bucket is located. Example: cn-hangzhou This parameter is required if you use the V4 signature algorithm.
    region = "cn-hangzhou"
    
    # Replace examplebucket with the name of the bucket. 
    bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)
    
    try:
        # If static website hosting is not enabled for the bucket, a NoSuchWebsite exception is thrown when you use get_bucket_website. 
        website = bucket.get_bucket_website()
        print('Index file is {0}, error file is {1}'.format(website.index_file, website.error_file))
    except oss2.exceptions.NoSuchWebsite as e:
        print('Website is not configured, request_id={0}'.format(e.request_id))           
  • Delete static website hosting configurations

    The following sample code provides an example on how to delete static website hosting configurations:

    #-*-coding:utf-8-*-
    import oss2
    from oss2.models import BucketWebsite
    from oss2.credentials import EnvironmentVariableCredentialsProvider
    
    # Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    
    # Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    # Specify the region in which the bucket is located. Example: cn-hangzhou This parameter is required if you use the V4 signature algorithm.
    region = "cn-hangzhou"
    
    # Replace examplebucket with the name of the bucket. 
    bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)
    
    # Delete the static website hosting configurations. 
    bucket.delete_bucket_website()           

Mirroring-based back-to-origin

Mirroring-based back-to-origin allows you to seamlessly migrate data to OSS. For example, you can migrate services from a self-managed origin or from another cloud service to OSS without causing a service interruption. You can use mirroring-based back-to-origin rules during migration to obtain data that is not migrated to OSS. This ensures business continuity.

  • Configure mirroring-based back-to-origin rules

    If a requester attempts to access an object in a specific bucket and the object does not exist, you can specify the URL of the object in the origin and back-to-origin conditions to allow the requester to obtain the object from the origin. For example, a bucket named examplebucket is located in the China (Hangzhou) region. When a requester attempts to access an object in the examplefolder directory of the root directory of the bucket but the object does not exist, the requester is redirected to its origin https://www.example.com/ to access the required object that is stored in the examplefolder directory of the origin.

    The following sample code provides an example on how to configure mirroring-based back-to-origin rules for the preceding scenario:

    #-*-coding:utf-8-*-
    import oss2
    from oss2.models import BucketWebsite, MirrorHeadersSet, RedirectMirrorHeaders, Redirect, RoutingRule, \
        REDIRECT_TYPE_MIRROR, Condition
    from oss2.credentials import EnvironmentVariableCredentialsProvider
    
    # Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    
    # Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    # Specify the region in which the bucket is located. Example: cn-hangzhou This parameter is required if you use the V4 signature algorithm.
    region = "cn-hangzhou"
    
    # Replace examplebucket with the name of the bucket. 
    bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)
    
    # Enable static website hosting, set the default homepage to index.html, and then set the default 404 page to error.html. 
    index_file = 'index.html'
    error_file = 'error.html'
    # Specify the matching conditions. 
    condition1 = Condition(key_prefix_equals='examplefolder',
                           http_err_code_return_equals=404)
    
    # Specify the headers that you want to include in the response when the requested object is obtained from the origin. 
    mirror_headers_set_1 = MirrorHeadersSet("myheader-key5", "myheader-value5")
    mirror_headers_set_2 = MirrorHeadersSet("myheader-key6", "myheader-value6")
    set_list = [mirror_headers_set_1, mirror_headers_set_2]
    pass_list = ['myheader-key1', 'myheader-key2']
    remove_list = ['myheader-key3', 'myheader-key4']
    mirror_header = RedirectMirrorHeaders(pass_all=True, pass_list=pass_list, remove_list=remove_list, set_list=set_list)
    # Specify the operation that you want to perform when the rule is matched. 
    redirect1 = Redirect(redirect_type=REDIRECT_TYPE_MIRROR, mirror_url='https://www.example.com/',
                         mirror_pass_query_string=True, mirror_follow_redirect=True, mirror_check_md5=True,
                         mirror_headers=mirror_header)
    
    rule1 = RoutingRule(rule_num=1, condition=condition1, redirect=redirect1)
    website_set = BucketWebsite(index_file, error_file, [rule1])
    
    # Configure the mirroring-based back-to-origin rule. 
    bucket.put_bucket_website(website_set)
  • Query mirroring-based back-to-origin configurations

    The following sample code provides an example on how to query mirroring-based back-to-origin configurations:

    #-*-coding:utf-8-*-
    import oss2
    from oss2.models import BucketWebsite, MirrorHeadersSet, RedirectMirrorHeaders, Redirect, RoutingRule, \
        REDIRECT_TYPE_MIRROR, Condition
    from oss2.credentials import EnvironmentVariableCredentialsProvider
    
    # Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    
    # Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    # Specify the region in which the bucket is located. Example: cn-hangzhou This parameter is required if you use the V4 signature algorithm.
    region = "cn-hangzhou"
    
    # Replace examplebucket with the name of the bucket. 
    bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)
    
    try:
        # If static website hosting is not enabled for the bucket, a NoSuchWebsite exception is thrown when you use get_bucket_website. 
        website_get = bucket.get_bucket_website()
        # Query the default homepage. 
        print(website_get.index_file)
        # Query the default 404 page. 
        print(website_get.error_file)
        for rule in website_get.rules:
            print(rule.rule_num)
            # Query the prefix that is used for rule matching. 
            print(rule.condition.key_prefix_equals)
            # Query the HTTP status code. 
            print(rule.condition.http_err_code_return_equals)
            # Query the redirection type. 
            print(rule.redirect.redirect_type)
            # Query the origin URL for mirroring-based back-to-origin. 
            print(rule.redirect.mirror_url)
            # Query the parameters in the request. 
            print(rule.redirect.pass_query_string)
            # Specify the string that is used to replace the object name when the request is redirected. The value of this parameter can be a variable. 
            # print(rule.redirect.replace_key_with)
            # Specify the string that is used to replace the prefix of the object name when the request is redirected. If the prefix of an object name is empty, the string precedes the object name. 
            # print(rule.redirect.replace_key_prefix_with)
            # Query the protocol that is used for redirection. 
            # print(rule.redirect.proto)
            # Query the domain name to which the request is redirected. 
            # print(rule.redirect.host_name)
            # Query the HTTP status code in the response. 
            # print(rule.redirect.http_redirect_code)
    except oss2.exceptions.NoSuchWebsite as e:
        print('Website is not configured, request_id={0}'.format(e.request_id))
  • Delete mirroring-based back-to-origin configurations

    The following sample code provides an example on how to delete mirroring-based back-to-origin configurations:

    #-*-coding:utf-8-*-
    import oss2
    from oss2.credentials import EnvironmentVariableCredentialsProvider
    
    # Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    
    # Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    # Specify the region in which the bucket is located. Example: cn-hangzhou This parameter is required if you use the V4 signature algorithm.
    region = "cn-hangzhou"
    
    # Replace examplebucket with the name of the bucket. 
    bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)
    
    # Delete the mirroring-based back-to-origin configurations. 
    bucket.delete_bucket_website()           

References

  • For more information about the API operation that you can call to configure static website hosting or mirroring-based back-to-origin, see PutBucketWebsite.

  • For more information about the API operation that you can call to query static website hosting or mirroring-based back-to-origin configurations, see GetBucketWebsite.

  • For more information about the API operation that you can call to delete static website hosting or mirroring-based back-to-origin configurations, see DeleteBucketWebsite.