Static websites are websites in which all web pages consist of only static content, including scripts such as JavaScript code that can be run on the client. You can use the static website hosting feature to host your static website on an Object Storage Service (OSS) bucket and use the domain name of the bucket to access the website.

Instructions

When you configure static website hosting, you must specify the default homepage and the default 404 page for the website.
  • The default homepage that appears when you use a browser to access the static website that is hosted on the OSS bucket.

    The object that you specify as the default homepage must be an object that is stored in the root directory of the bucket and allows anonymous access. If you enable Subfolder Homepage, the object must also be stored in the subdirectory.

  • The default 404 page is the error page that is returned by OSS. When you use a browser to access the static website that is hosted on an OSS bucket and a 404 error occurs, OSS returns the default 404 page.

    The object that you specify as the default 404 page must be an object that is stored in the root directory of the bucket and allows anonymous access.

To allow anonymous users to access the object, you must set the access control list (ACL) of the object that is specified as the default homepage or default 404 page to public-read. For more information about how to configure the ACLs of objects, see Configure ACLs for objects.

Usage notes

For security reasons, from September 28, 2018 for regions in the Chinese mainland, and September 25, 2019 for regions outside the Chinese mainland, the following limits take effect when you access static web page objects whose MIME type is text/html and whose name extension is HTM, HTML, JSP, PLG, HTX, or STM by using browsers:

  • When you use the default OSS domain name to access a static web page object, the following header is automatically added to the response: Content-Disposition:attachment. When you use a browser to access an object, the object is downloaded as an attachment.
  • When you use a custom domain name to access a static web page object by using a browser that can preview the web page object of the corresponding format, the object content is previewed.

Configuration examples

After you host a static website on a bucket, you must upload an object whose name is the same as that of the default homepage to the bucket. Example: index.html. If the bucket contains a directory named subdir/, you must upload the index.html object to the directory. In addition, you must upload an object whose name is the same as that of the default 404 page to the bucket. Example: error.html. The following section shows the structure of the objects and directories in the sample bucket:
Bucket
 ├── index.html
 ├── error.html
 ├── example.txt
 └── subdir/
      └── index.html
In this example, the custom domain name example.com is mapped to the bucket, the default homepage of the static website that is hosted on the bucket is index.html, and the default 404 page of the website is error.html. When you access the static website by using the custom domain name, OSS returns different responses based on your configurations of Static Pages for the bucket that hosts the website.
  • If Subfolder Homepage is disabled
    • When you access https://example.com/ and https://example.com/subdir/, OSS returns https://example.com/index.html.
    • When you access https://example.com/example.txt, the example.txt object is obtained.
    • When you access https://example.com/object, OSS returns https://example.com/error.html if the object object does not exist.
  • If Subfolder Homepage is enabled
    • When you access https://example.com/, OSS returns https://example.com/index.html.
    • When you access https://example.com/subdir/, OSS returns https://example.com/subdir/index.html.
    • When you access https://example.com/example.txt, the example.txt object is obtained.
    • When you access https://example.com/object, OSS returns one of the following responses based on your configurations for Subfolder 404 Rule because the object object does not exist:
      • If Subfolder 404 Rule is set to the default value Redirect, OSS continues to check whether object/index.html exists. If object/index.html exists, OSS returns the HTTP status code 302 and redirects the request to https://example.com/object/index.html. If object/index.html does not exist, OSS returns the HTTP status code 404 and checks whether https://example.com/error.html exists.
      • If Subfolder 404 Rule is set to NoSuchKey, OSS returns the HTTP status code 404 and checks whether https://example.com/error.html exists.
      • If Subfolder 404 Rule is set to Index, OSS continues to check whether the object/index.html object exists. If the object exists, OSS returns the HTTP status code 200 and the content of the object. If the object does not exist, OSS checks whether https://example.com/error.html exists.

Use the OSS console

  1. Configure static website hosting.
    • If Subfolder Homepage is disabled

      In the preceding example, when you access the subdir/ subdirectory of the bucket, the default homepage object named index.html in the root directory of the bucket is returned instead of the object named index.html in the subdir/ subdirectory. In addition, if you access an object that does not exist in the bucket, the specified default 404 page is returned. Perform the following steps to configure static website hosting:

      1. Log on to the OSS console.
      2. In the left-side navigation pane, click Buckets. On the Buckets page, click the name of the desired bucket.
      3. In the left-side navigation pane, choose Data Management > Static Pages.
      4. In the Static Pages section, click Configure and configure the parameters. The following table describes the parameters. Static Pages
        Parameter Description
        Default Homepage The default homepage that appears when you use a browser to access the static website that is hosted on the OSS bucket. In this example, set this parameter to index.html.
        Subfolder Homepage Specifies whether to enable Subfolder Homepage for the bucket. In this example, select Disable. In this case, when you access the root directory of the bucket or a subdirectory whose URL ends with a forward slash (/), the default homepage object in the root directory of the bucket is returned.
        Default 404 Page The error page that is returned if the object that you want to access does not exist in the bucket and HTTP status code 404 is returned. Only an object in the root directory of the bucket can be specified as the default 404 page. In this example, set this parameter to error.html.
        Error Page Status Code The HTTP status code that is returned with the error page. Valid values: 404 and 200.
      5. Click Save.
    • If Subfolder Homepage is enabled

      In the preceding example, when you access the subdir/ subdirectory of the bucket, the default homepage object named index.html in the subdirectory of the bucket is returned. In addition, if you access an object that does not exist in the bucket, the specified default 404 page and a result based on the specified subdirectory 404 rule are returned. Perform the following steps to configure static website hosting:

      1. In the Static Pages section, click Configure and configure the parameters. The following table describes the parameters. Static Pages 2
        Parameter Description
        Default Homepage The default homepage that appears when you use a browser to access the static website that is hosted on the OSS bucket. In this example, set this parameter to index.html.
        Subfolder Homepage Specifies whether to enable Subfolder Homepage for the bucket. In this example, select Enable. After you enable Subfolder Homepage for a bucket, if you access the root directory of the bucket, the default homepage in the root directory is returned. If you access a subdirectory whose URL ends with a forward slash (/), the default homepage in the subdirectory is returned. For example, if you access https://examplebucket.oss-cn-hangzhou.aliyuncs.com/subdir/, the default homepage object index.html in the subdir/ directory is returned.
        Subfolder 404 Rule The subdirectory 404 rule for the bucket. When you access an object that does not exist in the bucket, OSS returns different results based on the specified subdirectory 404 rule. For example, if you use the URL https://examplebucket.oss-cn-hangzhou.aliyuncs.com/exampledir to access an object named exampledir that does not exist in the bucket, OSS returns different results based on the value that you set for this parameter. Default value: Redirect. Valid values:
        • Redirect: OSS checks whether the exampledir/index.html object exists.
          • If the object exists, OSS returns the HTTP status code 302 and redirects the request to https://examplebucket.oss-cn-hangzhou.aliyuncs.com/exampledir/index.html.
          • If the object does not exist, OSS returns the HTTP status code 404 and checks whether the https://examplebucket.oss-cn-hangzhou.aliyuncs.com/error.html object exists. If the object does not exist, OSS returns the HTTP status code 404.
        • NoSuchKey: OSS returns the HTTP status code 404 and checks whether the https://examplebucket.oss-cn-hangzhou.aliyuncs.com/error.html object exists.
        • Index: OSS checks whether the exampledir/index.html object exists.
          • If the object exists, OSS returns the HTTP status code 200 and the content of the object.
          • If the object does not exist, OSS checks whether the https://examplebucket.oss-cn-hangzhou.aliyuncs.com/error.html object exists.
        Default 404 Page The error page that is returned if the object that you want to access does not exist in the bucket and HTTP status code 404 is returned. Only an object in the root directory of the bucket can be specified as the default 404 page. In this example, set this parameter to error.html.
        Error Page Status Code The HTTP status code that is returned with the error page. Valid values: 404 and 200.
      2. Click Save.
  2. Create and upload a default homepage object.
    If you set the default homepage to index.html when you configure static website hosting for the examplebucket bucket, you must upload an object named index.html to the root directory of the bucket. If you enable Subfolder Homepage for the bucket, you must also upload index.html to the subdir/ subdirectory of the bucket.
    1. Create a file named index.html. The content of the index.html file is similar to the following example:
      <html>
      <head>
          <title>My Website Home Page</title>
          <meta charset="utf-8">
      </head>
      <body>  
        <p>Now hosted on OSS.</p>
      </body>
      </html>
    2. Save index.html to a local path.
    3. Upload index.html to the root directory and subdir/ subdirectory of examplebucket. You must set the ACL of the index.html object to public read.

      For more information about how to upload objects, see Simple upload.

  3. Create and upload a default 404 page.
    If you set the default 404 page to error.html when you configure static website hosting for examplebucket, you must upload an object named error.html to the root directory of examplebucket.
    1. Create a file named error.html. The content of the error.html file is similar to the following example:
      <html>
      <head>
          <title>Hello OSS!</title>
          <meta charset="utf-8">
      </head>
      <body>  
        <p>This is error 404 page.</p>
      </body>
      </html>
    2. Save error.html to a local path.
    3. Upload error.html to the root directory of examplebucket. You must set the ACL of the index.html object to public read.

Use OSS SDKs

The following code provides examples on how to configure static website hosting by using OSS SDKs for common programming languages. For more information about how to configure static website hosting by using OSS SDKs for other programming languages, see Overview.

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.SetBucketWebsiteRequest;

public class Demo {

    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
        String accessKeyId = "yourAccessKeyId";
        String accessKeySecret = "yourAccessKeySecret";
        // Specify the bucket name. Example: examplebucket. 
        String bucketName = "examplebucket";

        // Create an OSSClient instance. 
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // Specify the bucket name. 
            SetBucketWebsiteRequest request = new SetBucketWebsiteRequest(bucketName);
            // Specify the default homepage of the static website hosted on the bucket. 
            request.setIndexDocument("index.html");
            // Specify the default 404 page of the static website hosted on the bucket. 
            request.setErrorDocument("error.html");
            ossClient.setBucketWebsite(request);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\OssClient;
use OSS\Core\OssException;
use OSS\Model\WebsiteConfig;

// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in Object Storage Service (OSS) is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
$accessKeyId = "yourAccessKeyId";
$accessKeySecret = "yourAccessKeySecret";
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the bucket name. Example: examplebucket. 
$bucket= "examplebucket";

// Set the default homepage to index.html and the default 404 page to error.html for the static website hosted on the bucket. 
$websiteConfig = new WebsiteConfig("index.html", "error.html");
try {
    $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

    $ossClient->putBucketWebsite($bucket, $websiteConfig);
} catch (OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}
print(__FUNCTION__ . ": OK" . "\n");
            
# -*- coding: utf-8 -*-
import oss2
from oss2.models import *

# The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
auth = oss2.Auth('yourAccessKeyId', 'yourAccessKeySecret')
# In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
# Specify the name of the bucket. Example: examplebucket. 
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')

# Enable static website hosting and set the default homepage to index.html and the default 404 page to error.html. 
bucket.put_bucket_website(BucketWebsite('index.html', 'error.html'))            
package main

import (
    "fmt"
    "os"
    "github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
    // Create an OSSClient instance. 
    // Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set yourEndpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify the endpoint based on your business requirements. 
    // Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to access OSS because the account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine operations and maintenance. To create a RAM user, log on to the RAM console. 
    client, err := oss.New("yourEndpoint", "yourAccessKeyId", "yourAccessKeySecret")
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
    // Specify the name of the bucket. Example: examplebucket. 
    bucketName := "examplebucket"

    // Set the default homepage to index.html and the default 404 page to error.html for the static website that is hosted in the bucket. 
    err = client.SetBucketWebsite(bucketName, "index.html", "error.html")
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
}            
using Aliyun.OSS;
using Aliyun.OSS.Common;

// Set yourEndpoint to 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. 
var endpoint = "yourEndpoint";
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in Object Storage Service (OSS) is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
var accessKeyId = "yourAccessKeyId";
var accessKeySecret = "yourAccessKeySecret";
// Specify the bucket name. 
var bucketName = "examplebucket";

// Create an OSSClient instance. 
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try
{
    // Set the default homepage to index.html and the default 404 page to error.html for the static website hosted on the bucket. 
    var request = new SetBucketWebsiteRequest(bucketName, "index.html", "error.html");
    client.SetBucketWebsite(request);
    Console.WriteLine("Set bucket:{0} Wetbsite succeeded ", bucketName);
}
catch (OssException ex)
{
    Console.WriteLine("Failed with error info: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
        ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
    Console.WriteLine("Failed with error info: {0}", ex.Message);
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize the information about the account that is used to access Object Storage Service (OSS). */
    /* The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. */
    std::string AccessKeyId = "yourAccessKeyId";
    std::string AccessKeySecret = "yourAccessKeySecret";
    /* 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. */
    std::string Endpoint = "yourEndpoint";
    /* Specify the bucket name. Example: examplebucket. */
    std::string BucketName = "examplebucket";

    /* Initialize resources such as networks. */
    InitializeSdk();

    ClientConfiguration conf;
    OssClient client(Endpoint, AccessKeyId, AccessKeySecret,  conf);

    /* Configure static website hosting. */
    SetBucketWebsiteRequest request(BucketName);
    /* Set the default homepage to index.html for the static website hosted on the bucket. */
    request.setIndexDocument("index.html");
    /* Set the default 404 page to error.html for the static website hosted on the bucket. */
    request.setErrorDocument("error.html");

    auto outcome = client.SetBucketWebsite(request);

    if (!outcome.isSuccess()) {
        /* Handle exceptions. */
        std::cout << "SetBucketWebsite fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        ShutdownSdk();
        return -1;
    }

    /* Release resources such as networks. */
    ShutdownSdk();
    return 0;
}

Use RESTful APIs

If your business requires a high level of customization, you can directly call RESTful APIs. To directly call an API, you must include the signature calculation in your code. For more information, see PutBucketWebsite.

FAQ

Can I disable the static website hosting feature after I enabled the feature for a bucket?

If you no longer need to use the configurations of static website hosting, perform the following steps to disable the static website hosting feature:

  1. In the left-side navigation pane, choose Data Management > Static Pages.
  2. Remove the configurations of the Default Homepage and Default 404 Page parameters and click Save.
    If a similar figure is returned, the static website hosting feature is disabled. close

References