Updated on 2026-07-31 GMT+08:00

Static Website Hosting (SDK for Python)

Function

This API uploads the files of the static website to your bucket in OBS as objects and configures the public-read permission on the files, and then configures the static website hosting mode for your bucket to host your static websites in OBS. After this, when third-party users access your websites, they actually access the objects in your bucket in OBS. When using static website hosting, you can configure request redirection to redirect specific or all requests.

For more information, see Static Website Hosting.

Restrictions

Uploading a Website File to a Bucket

1. Upload the website files to your bucket in OBS as objects and set the MIME type for the objects.

2. Set the object ACL to public read.

3. Access the objects using a browser.

This example uploads an HTML website file to a bucket and grants the public read permission for the object to implement static website hosting.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import os
import traceback

from obs import HeadPermission
from obs import ObsClient
from obs import PutObjectHeader

# Obtain an AK/SK pair using environment variables (recommended) or import it in other ways. Using hard coding may result in leakage.
# Obtain an AK and SK pair on the management console. For details, see https://support.huaweicloud.com/intl/en-us/usermanual-ca/ca_01_0003.html.
ak = os.getenv("AccessKeyID")
sk = os.getenv("SecretAccessKey")
# If you use a temporary AK/SK pair and a security token to access OBS, obtain them from environment variables.
# security_token = os.getenv("SecurityToken")
# Set server to the endpoint corresponding to the bucket. CN-Hong Kong is used here as an example. Replace it with the one currently in use.
server = "https://obs.ap-southeast-1.myhuaweicloud.com"

# Create an obsClient instance.
# If you use a temporary AK/SK pair and a security token to access OBS, you must specify security_token when creating an instance.
obs_client = ObsClient(access_key_id=ak, secret_access_key=sk, server=server)
try:
    bucket_name = 'bucketname'
    # Specify a website file name.
    object_key = 'test.html'
# Specify the path of a local HTML website file.
    file_path = 'localfile.html'
    headers = PutObjectHeader()
    # Specify the MIME type for the object.
    headers.contentType = 'text/html'

    # Upload the object.
    resp = obs_client.putFile(bucket_name, object_key, file_path, headers=headers)

    # If status code 2xx is returned, the API is called successfully. Otherwise, the API call fails.
    if resp.status < 300:
        print('Put File Succeeded')
        print('requestId:', resp.requestId)
        # Set the object ACL to public read.
        resp2 = obs_client.setObjectAcl(bucket_name, object_key, aclControl=HeadPermission.PUBLIC_READ)
        if resp2.status < 300:
            print('Set Object Acl Succeeded')
            print('requestId:', resp2.requestId)
        else:
            print('Set Object Acl Failed')
            print('requestId:', resp2.requestId)
            print('errorCode:', resp2.errorCode)
            print('errorMessage:', resp2.errorMessage)
    else:
        print('Put File Failed')
        print('requestId:', resp.requestId)
        print('errorCode:', resp.errorCode)
        print('errorMessage:', resp.errorMessage)
except Exception:
    print('Put File Failed')
    print(traceback.format_exc())

You can use https://bucketname.your-endpoint/test.html in a browser to access files hosted using the sample code.

Configuring Static Website Hosting

This example configures static website hosting for bucket examplebucket.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import os
import traceback

from obs import Condition
from obs import ErrorDocument
from obs import IndexDocument
from obs import ObsClient
from obs import Redirect
from obs import RoutingRule
from obs import WebsiteConfiguration

# Obtain an AK/SK pair using environment variables (recommended) or import it in other ways. Using hard coding may result in leakage.
# Obtain an AK and SK pair on the management console. For details, see https://support.huaweicloud.com/intl/en-us/usermanual-ca/ca_01_0003.html.
ak = os.getenv("AccessKeyID")
sk = os.getenv("SecretAccessKey")
# If you use a temporary AK/SK pair and a security token to access OBS, obtain them from environment variables.
# security_token = os.getenv("SecurityToken")
# Set server to the endpoint corresponding to the bucket. CN-Hong Kong is used here as an example. Replace it with the one currently in use.
server = "https://obs.ap-southeast-1.myhuaweicloud.com"

# Create an obsClient instance.
# If you use a temporary AK/SK pair and a security token to access OBS, you must specify security_token when creating an instance.
obs_client = ObsClient(access_key_id=ak, secret_access_key=sk, server=server)
try:
    # Specify an error page when a 4XX error occurs.
    error_document = ErrorDocument(key='error.html')
    # Specify a default page.
    index_document = IndexDocument(suffix='index.html')
    # Specify a rule for redirecting requests to NotFound.html if the status code is 404.
    routing_rule1 = RoutingRule(condition=Condition(httpErrorCodeReturnedEquals=404),
                               redirect = Redirect(protocol='http', replaceKeyWith='NotFound.html'))
    # Configure the redirection rules in list format. Multiple rules can be configured.
    routing_rules = [routing_rule1]
    bucket_name = "examplebucket"
    # Configure static website hosting for the bucket.
    resp = obs_client.setBucketWebsite(bucket_name,
                                      WebsiteConfiguration(errorDocument=error_document, indexDocument=index_document,
                                                           routing_rules = routing_rules))

    # If status code 2xx is returned, the API is called successfully. Otherwise, the API call fails.
    if resp.status < 300:
        print('Set Bucket Website Succeeded')
        print('requestId:', resp.requestId)
    else:
        print('Set Bucket Website Failed')
        print('requestId:', resp.requestId)
        print('errorCode:', resp.errorCode)
        print('errorMessage:', resp.errorMessage)
except Exception:
    print('Set Bucket Website Failed')
    print(traceback.format_exc())

This example configures redirection for all requests.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import os
import traceback

from obs import ObsClient
from obs import RedirectAllRequestTo
from obs import WebsiteConfiguration

# Obtain an AK/SK pair using environment variables (recommended) or import it in other ways. Using hard coding may result in leakage.
# Obtain an AK and SK pair on the management console. For details, see https://support.huaweicloud.com/intl/en-us/usermanual-ca/ca_01_0003.html.
ak = os.getenv("AccessKeyID")
sk = os.getenv("SecretAccessKey")
# If you use a temporary AK/SK pair and a security token to access OBS, obtain them from environment variables.
# security_token = os.getenv("SecurityToken")
# Set server to the endpoint corresponding to the bucket. CN-Hong Kong is used here as an example. Replace it with the one currently in use.
server = "https://obs.ap-southeast-1.myhuaweicloud.com" 

# Create an obsClient instance.
# If you use a temporary AK/SK pair and a security token to access OBS, you must specify security_token when creating an instance.
obs_client = ObsClient(access_key_id=ak, secret_access_key=sk, server=server)
try:
    bucket_name = 'bucketname'
    # Configure redirection for all requests.
    resp = obs_client.setBucketWebsite(bucket_name,
                                       WebsiteConfiguration(
                                           redirect_all_request_to = RedirectAllRequestTo(hostName='www.example.com',
                                                                                     protocol = 'http')))
    if resp.status < 300:
        print('Set Bucket Website Succeeded')
        print('requestId:', resp.requestId)
    else:
        print('Set Bucket Website Failed')
        print('requestId:', resp.requestId)
        print('errorCode:', resp.errorCode)
        print('errorMessage:', resp.errorMessage)
except Exception:
    print('Set Bucket Website Failed')
    print(traceback.format_exc())

Viewing Static Website Hosting

This example returns the static website hosting configuration of bucket examplebucket.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import os
import traceback

from obs import ObsClient

# Obtain an AK/SK pair using environment variables (recommended) or import it in other ways. Using hard coding may result in leakage.
# Obtain an AK and SK pair on the management console. For details, see https://support.huaweicloud.com/intl/en-us/usermanual-ca/ca_01_0003.html.
ak = os.getenv("AccessKeyID")
sk = os.getenv("SecretAccessKey")
# If you use a temporary AK/SK pair and a security token to access OBS, obtain them from environment variables.
# security_token = os.getenv("SecurityToken")
# Set server to the endpoint corresponding to the bucket. CN-Hong Kong is used here as an example. Replace it with the one currently in use.
server = "https://obs.ap-southeast-1.myhuaweicloud.com"

# Create an obsClient instance.
# If you use a temporary AK/SK pair and a security token to access OBS, you must specify security_token when creating an instance.
obs_client = ObsClient(access_key_id=ak, secret_access_key=sk, server=server)
try:
    bucket_name = "examplebucket"
    # Obtain the static website configuration of the bucket.
    resp = obs_client.getBucketWebsite(bucket_name)
    # If status code 2xx is returned, the API is called successfully. Otherwise, the API call fails.
    if resp.status < 300:
        print('Get Bucket Website Succeeded')
        print('requestId:', resp.requestId)
        if resp.body.redirect_all_request_to:
            print('redirectAllRequestTo.hostName:', resp.body.redirect_all_request_to.hostName,
                  ',redirectAllRequestTo.protocol:', resp.body.redirect_all_request_to.protocol)
        if resp.body.index_document:
            print('indexDocument.suffix:', resp.body.index_document.suffix)
        if resp.body.error_document:
            print('errorDocument.key:', resp.body.error_document.key)
        if resp.body.routing_rules:
            index = 1
            for rout in resp.body.routing_rules:
                print('routingRule[', index, ']:')
                index += 1
                print('condition.keyPrefixEquals:', rout.condition.keyPrefixEquals,
                      ',condition.httpErrorCodeReturnedEquals:', rout.condition.httpErrorCodeReturnedEquals)
                print('redirect.protocol:', rout.redirect.protocol, ',redirect.hostName:', rout.redirect.hostName,
                      ',redirect.replaceKeyPrefixWith:', rout.redirect.replaceKeyPrefixWith,
                      ',redirect.replaceKeyWith:', rout.redirect.replaceKeyWith, ',redirect.httpRedirectCode:',
                      rout.redirect.httpRedirectCode)
    else:
        print('Get Bucket Website Failed')
        print('requestId:', resp.requestId)
        print('errorCode:', resp.errorCode)
        print('errorMessage:', resp.errorMessage)
except Exception:
    print('Get Bucket Website Failed')
    print(traceback.format_exc())

Deleting Static Website Hosting

This example deletes the static website hosting configuration of bucket examplebucket.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import os
import traceback

from obs import ObsClient

# Obtain an AK/SK pair using environment variables (recommended) or import it in other ways. Using hard coding may result in leakage.
# Obtain an AK and SK pair on the management console. For details, see https://support.huaweicloud.com/intl/en-us/usermanual-ca/ca_01_0003.html.
ak = os.getenv("AccessKeyID")
sk = os.getenv("SecretAccessKey")
# If you use a temporary AK/SK pair and a security token to access OBS, obtain them from environment variables.
# security_token = os.getenv("SecurityToken")
# Set server to the endpoint corresponding to the bucket. CN-Hong Kong is used here as an example. Replace it with the one currently in use.
server = "https://obs.ap-southeast-1.myhuaweicloud.com" 

# Create an obsClient instance.
# If you use a temporary AK/SK pair and a security token to access OBS, you must specify security_token when creating an instance.
obs_client = ObsClient(access_key_id=ak, secret_access_key=sk, server=server)
try:
    bucket_name = "examplebucket"
    # Delete the static website hosting configuration of the bucket.
    resp = obs_client.deleteBucketWebsite(bucket_name)

    # If status code 2xx is returned, the API is called successfully. Otherwise, the API call fails.
    if resp.status < 300:
        print('Delete Bucket Website Succeeded')
        print('requestId:', resp.requestId)
    else:
        print('Delete Bucket Website Failed')
        print('requestId:', resp.requestId)
        print('errorCode:', resp.errorCode)
        print('errorMessage:', resp.errorMessage)
except Exception:
    print('Delete Bucket Website Failed')
    print(traceback.format_exc())