Help Center/ Object Storage Service/ SDK Reference/ Python/ Bucket-Related APIs (SDK for Python)/ Configuring Static Website Hosting for a Bucket (SDK for Python)
Updated on 2024-09-05 GMT+08:00

Configuring Static Website Hosting for a Bucket (SDK for Python)

Function

You can host static website resources such as HTML web pages, flash files, or audio and video files in an OBS bucket, so that you can provide these hosted resources using the bucket's website endpoint to end users. Typical use cases include:

  • Redirecting all requests to another website
  • Redirecting specific requests

This API configures static website hosting for a bucket.

Restrictions

  • Periods (.) should be avoided in the target bucket name, or there may be certificate verification failures on the client when you use HTTPS for access.
  • The request body of the website configuration cannot exceed 10 KB.
  • To configure static website hosting for a bucket, you must be the bucket owner or have the required permission (obs:bucket:PutBucketWebsite in IAM or PutBucketWebsite in a bucket policy). For details, see Introduction to OBS Access Control, IAM Custom Policies, and Creating a Custom Bucket Policy.

Method

ObsClient.setBucketWebsite(bucketName, website)

Request Parameters

Parameter

Type

Mandatory (Yes/No)

Description

bucketName

str

Yes

Explanation:

Bucket name

Restrictions:

  • A bucket name must be unique across all accounts and regions.
  • A bucket name:
    • Must be 3 to 63 characters long and start with a digit or letter. Lowercase letters, digits, hyphens (-), and periods (.) are allowed.
    • Cannot be formatted as an IP address.
    • Cannot start or end with a hyphen (-) or period (.).
    • Cannot contain two consecutive periods (..), for example, my..bucket.
    • Cannot contain periods (.) and hyphens (-) adjacent to each other, for example, my-.bucket or my.-bucket.
  • If you repeatedly create buckets of the same name in the same region, no error will be reported and the bucket properties comply with those set in the first creation request.

Default value:

None

website

WebsiteConfiguration

Yes

Explanation:

Input parameters for configuring static website hosting. For details, see Table 1.

Default value:

None

Table 1 WebsiteConfiguration

Parameter

Type

Mandatory (Yes/No)

Description

redirectAllRequestTo

RedirectAllRequestTo

No if used as a request parameter

Explanation:

Redirection rules for all requests. For details, see Table 2.

Default value:

None

indexDocument

IndexDocument

No if used as a request parameter

Explanation:

Default page configuration. For details, see Table 3.

Default value:

None

errorDocument

ErrorDocument

No if used as a request parameter

Explanation:

Error page configuration. For details, see Table 4.

Default value:

None

routingRules

list of RoutingRule

No if used as a request parameter

Explanation:

List of routing rules. For details, see Table 5.

Default value:

None

  • errorDocument, indexDocument, and routingRules must be used together and they cannot be used with redirectAllRequestsTo.
  • When errorDocument, indexDocument, and routingRules are used together, routingRules can be left blank.
  • You must specify either the combo of fields ErrorDocument, IndexDocument, and RoutingRules, or the RedirectAllRequestsTo field.
Table 2 RedirectAllRequestTo

Parameter

Type

Mandatory (Yes/No)

Description

hostName

str

Yes if used as a request parameter

Explanation:

Host name used for redirection, for example, www.example.com

Restrictions:

The host name must comply with the host name rules.

Default value:

None

protocol

str

No if used as a request parameter

Explanation:

Protocol used for redirection

Value range:

  • http
  • https

Default value:

None

Table 3 IndexDocument

Parameter

Type

Mandatory (Yes/No)

Description

suffix

str

Yes if used as a request parameter

Explanation:

Suffix that is appended to the request for a directory. For example, if the suffix is index.html and you request samplebucket/images/, the returned data will be for the object named images/index.html in the bucket samplebucket.

Value range:

This parameter can neither be left blank nor contain slashes (/).

Default value:

None

Table 4 ErrorDocument

Parameter

Type

Mandatory (Yes/No)

Description

key

str

No if used as a request parameter

Explanation:

Object name to use when a 4XX error occurs. This parameter specifies the webpage to display when an error occurs.

Value range:

The value must contain 1 to 1,024 characters.

Default value:

None

Table 5 RoutingRule

Parameter

Type

Mandatory (Yes/No)

Description

condition

Condition

No if used as a request parameter

Explanation:

Conditions that must be met for the specified redirect to apply

Value range:

See Table 6.

Default value:

None

redirect

Redirect

Yes if used as a request parameter

Explanation:

Details about the redirection. For details, see Table 7.

Default value:

None

Table 6 Condition

Parameter

Type

Mandatory (Yes/No)

Description

keyPrefixEquals

str

No if used as a request parameter

Explanation:

Object name prefix for the redirection to take effect. If the name prefix of the requested object is the same as the value specified for this parameter, the redirection rule takes effect.

For example, to redirect the requests for the object ExamplePage.html, set KeyPrefixEquals to ExamplePage.html.

Restrictions:

This parameter cannot be used together with httpErrorCodeReturnedEquals.

Value range:

The value must contain 1 to 1,024 characters.

Default value:

None

httpErrorCodeReturnedEquals

int

No if used as a request parameter

Explanation:

HTTP error code for the redirection to take effect. If there is an error, and the error code returned is the same as the value specified for this parameter, the redirection rule takes effect.

For example, if you want to redirect requests to NotFound.html when HTTP error code 404 is returned, set httpErrorCodeReturnedEquals to 404 in Condition, and set ReplaceKeyWith to NotFound.html in Redirect.

Restrictions:

This parameter cannot be used together with keyPrefixEquals.

Value range:

See Error Codes.

Default value:

None

Table 7 Redirect

Parameter

Type

Mandatory (Yes/No)

Description

protocol

str

No if used as a request parameter

Explanation:

Protocol used for redirection

Value range:

  • http
  • https

Default value:

None

hostName

str

No if used as a request parameter

Explanation:

Host name used for redirection

Default value:

None

replaceKeyPrefixWith

str

No if used as a request parameter

Explanation:

Object name prefix used in the redirection request

Value range:

The value must contain 1 to 1,024 characters.

Default value:

None

replaceKeyWith

str

No if used as a request parameter

Explanation:

Object name used in the redirection request

Restrictions:

This parameter cannot be used together with replaceKeyPrefixWith.

Value range:

The value must contain 1 to 1,024 characters.

Default value:

None

httpRedirectCode

int

No if used as a request parameter

Explanation:

HTTP status code in the response to the redirect request. For details, see Status Code.

Default value:

None

Responses

Type

Description

GetResult

Explanation:

SDK common results

Table 8 GetResult

Parameter

Type

Description

status

int

Explanation:

HTTP status code

Value range:

A status code is a group of digits ranging from 2xx (indicating successes) to 4xx or 5xx (indicating errors). It indicates the status of a response. For more information, see Status Code.

Default value:

None

reason

str

Explanation:

Reason description.

Default value:

None

errorCode

str

Explanation:

Error code returned by the OBS server. If the value of status is less than 300, this parameter is left blank.

Default value:

None

errorMessage

str

Explanation:

Error message returned by the OBS server. If the value of status is less than 300, this parameter is left blank.

Default value:

None

requestId

str

Explanation:

Request ID returned by the OBS server

Default value:

None

indicator

str

Explanation:

Error indicator returned by the OBS server.

Default value:

None

hostId

str

Explanation:

Requested server ID. If the value of status is less than 300, this parameter is left blank.

Default value:

None

resource

str

Explanation:

Error source (a bucket or an object). If the value of status is less than 300, this parameter is left blank.

Default value:

None

header

list

Explanation:

Response header list, composed of tuples. Each tuple consists of two elements, respectively corresponding to the key and value of a response header.

Default value:

None

body

object

Explanation:

Result content returned after the operation is successful. If the value of status is larger than 300, this parameter is left blank. The value varies with the API being called. For details, see Bucket-Related APIs (SDK for Python) and Object-Related APIs (SDK for Python).

Default value:

None

Code Examples

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
from obs import ObsClient
from obs import WebsiteConfiguration
from obs import IndexDocument
from obs import ErrorDocument
from obs import RoutingRule
from obs import Condition
from obs import Redirect
import os
import traceback

# Obtain an AK and SK pair using environment variables or import the AK and SK pair 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/eu/usermanual-ca/ca_01_0003.html.
ak = os.getenv("AccessKeyID")
sk = os.getenv("SecretAccessKey")
# (Optional) If you use a temporary AK and 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. Here uses EU-Dublin as an example. Replace it with the one in use.
server = "https://obs.eu-west-101.myhuaweicloud.eu" 

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

    # 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:
    print('Set Bucket Website Failed')
    print(traceback.format_exc())