All Products
Search
Document Center

Object Storage Service:Static website hosting (mirroring-based back-to-origin) (Python SDK V1)

Last Updated:Mar 20, 2026

Use the OSS SDK for Python 1.0 (oss2) to configure static website hosting and mirroring-based back-to-origin for a bucket. After you enable static website hosting, OSS serves the configured index page for directory requests and the error page for 404 responses. Mirroring-based back-to-origin lets you retrieve objects from an origin server when they don't yet exist in OSS—keeping your service running without interruption during a data migration.

Usage notes

  • Examples in this topic use the public endpoint for the China (Hangzhou) region. To access OSS from another Alibaba Cloud service in the same region, use an internal endpoint instead. For more information, see Regions and endpoints.

  • Access credentials in the examples are read from environment variables. For setup instructions, see Configure access credentials using OSS SDK for Python 1.0.

  • Examples create an OSSClient instance using an OSS endpoint. To create one using a custom domain name or Security Token Service (STS), see Initialization.

  • Required RAM permissions: For instructions on granting these permissions, see Grant custom permissions to a RAM user.

    OperationPermission
    Configureoss:PutBucketWebsite
    Queryoss:GetBucketWebsite
    Deleteoss:DeleteBucketWebsite

Prerequisites

Before you begin, ensure that you have:

  • An OSS bucket

  • The OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables configured with valid access credentials

  • The required RAM permission for the operation you want to perform

Static website hosting

Configure static website hosting

# -*- coding: utf-8 -*-
import oss2
from oss2.models import BucketWebsite
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Read credentials from the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Endpoint for the region where your bucket is located
# Format: https://oss-{region-id}.aliyuncs.com
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"

# Region ID — required when using the V4 signature algorithm
region = "cn-hangzhou"

bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)

# Configure static website hosting
# index.html: served for requests that map to a directory (e.g., /)
# error.html: served when a requested object does not exist (HTTP 404)
bucket.put_bucket_website(BucketWebsite('index.html', 'error.html'))

Query the configuration

get_bucket_website raises oss2.exceptions.NoSuchWebsite if static website hosting has not been enabled for the bucket.

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
region = "cn-hangzhou"
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)

try:
    website = bucket.get_bucket_website()
    print('Index page: {0}'.format(website.index_file))
    print('Error page: {0}'.format(website.error_file))
except oss2.exceptions.NoSuchWebsite as e:
    print('Static website hosting is not configured. Request ID: {0}'.format(e.request_id))

Delete the configuration

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
region = "cn-hangzhou"
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)

bucket.delete_bucket_website()

Mirroring-based back-to-origin

Use mirroring-based back-to-origin to migrate data to OSS without interrupting your service. When a request hits an object that doesn't yet exist in the bucket, OSS fetches it from the origin server and returns it to the requester transparently, without requiring changes on the client side.

Configure mirroring-based back-to-origin rules

The following example configures a mirroring rule for examplebucket in the China (Hangzhou) region. When a requester accesses an object under the examplefolder prefix that doesn't exist in the bucket (HTTP 404), OSS fetches it from https://www.example.com/.

The rule also demonstrates header forwarding: pass myheader-key1 and myheader-key2 from the origin response, strip myheader-key3 and myheader-key4, and inject myheader-key5 and myheader-key6 with fixed values.

# -*- coding: utf-8 -*-
import oss2
from oss2.models import (
    BucketWebsite,
    MirrorHeadersSet,
    RedirectMirrorHeaders,
    Redirect,
    RoutingRule,
    REDIRECT_TYPE_MIRROR,
    Condition,
)
from oss2.credentials import EnvironmentVariableCredentialsProvider

auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
region = "cn-hangzhou"
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)

index_file = 'index.html'
error_file = 'error.html'

# Condition: trigger when a request for an object with this key prefix returns HTTP 404
condition1 = Condition(
    key_prefix_equals='examplefolder',       # match objects whose key starts with this prefix
    http_err_code_return_equals=404,          # trigger only on 404 (object not found)
)

# Header forwarding rules applied to the origin response
mirror_headers_set_1 = MirrorHeadersSet("myheader-key5", "myheader-value5")
mirror_headers_set_2 = MirrorHeadersSet("myheader-key6", "myheader-value6")

mirror_header = RedirectMirrorHeaders(
    pass_all=True,
    pass_list=['myheader-key1', 'myheader-key2'],
    remove_list=['myheader-key3', 'myheader-key4'],
    set_list=[mirror_headers_set_1, mirror_headers_set_2],
)

# Redirect action: fetch the missing object from the origin server
redirect1 = Redirect(
    redirect_type=REDIRECT_TYPE_MIRROR,
    mirror_url='https://www.example.com/',
    mirror_pass_query_string=True,           # forward the original query string to the origin
    mirror_follow_redirect=True,             # follow redirects returned by the origin
    mirror_check_md5=True,                   # verify the MD5 hash of the origin response
    mirror_headers=mirror_header,
)

rule1 = RoutingRule(rule_num=1, condition=condition1, redirect=redirect1)
website_set = BucketWebsite(index_file, error_file, [rule1])

bucket.put_bucket_website(website_set)

Query mirroring-based back-to-origin configurations

get_bucket_website returns the index page, error page, and all routing rules. Each rule exposes its matching condition and redirect action.

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
region = "cn-hangzhou"
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)

try:
    website_get = bucket.get_bucket_website()

    print('Index page:', website_get.index_file)
    print('Error page:', website_get.error_file)

    for rule in website_get.rules:
        print('Rule number:', rule.rule_num)
        print('  Key prefix:', rule.condition.key_prefix_equals)
        print('  HTTP error code:', rule.condition.http_err_code_return_equals)
        print('  Redirect type:', rule.redirect.redirect_type)
        print('  Mirror URL:', rule.redirect.mirror_url)
        print('  Pass query string:', rule.redirect.pass_query_string)
        # print(rule.redirect.replace_key_with)
        # print(rule.redirect.replace_key_prefix_with)
        # print(rule.redirect.proto)
        # print(rule.redirect.host_name)
        # print(rule.redirect.http_redirect_code)

except oss2.exceptions.NoSuchWebsite as e:
    print('Static website hosting is not configured. Request ID: {0}'.format(e.request_id))

Delete mirroring-based back-to-origin configurations

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
region = "cn-hangzhou"
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)

bucket.delete_bucket_website()

API reference

TaskAPI operation
Configure static website hosting or mirroring-based back-to-originPutBucketWebsite
Query configurationsGetBucketWebsite
Delete configurationsDeleteBucketWebsite