All Products
Search
Document Center

Object Storage Service:Overview

Last Updated:Mar 08, 2024

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 a 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.

How it works

When you enable the static website hosting feature, you must specify the default homepage and the default 404 page for the website.

  • The default homepage 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 ACL for objects.

Usage notes

To ensure security, 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 example

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 bound 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.

Configure static website hosting

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. To configure static website hosting, perform the following steps:

      1. Log on to the OSS console.

      2. In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.

      3. In the left-side navigation pane, choose Data Management > Static Page.

      4. On the Static Page page, click Settings and configure the parameters. The following table describes the parameters.静态页面

        Parameter

        Description

        Default Homepage

        The default homepage appears when you use a browser to access the static website that is hosted on the OSS bucket. In this example, this parameter is set 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, this parameter is set 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. To configure static website hosting, perform the following steps:

      1. On the Static Page page, click Settings and configure the parameters. The following table describes the parameters.静态页面2

        Parameter

        Description

        Default Homepage

        The default homepage appears when you use a browser to access the static website that is hosted on the OSS bucket. In this example, this parameter is set 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 named index.html in the subdir/ directory is returned.

        Subfolder 404 Rule

        The subdirectory 404 rule of the bucket when the Subfolder Homepage feature is enabled. 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 specify for this parameter. Valid values:

        • Redirect (default): 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 this 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, this parameter is set 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 the index.html object 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 the index.html file to a local path.

    3. Upload the index.html file to the root directory and subdir/ subdirectory of the examplebucket bucket. 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 the examplebucket bucket, you must upload an object named error.html to the root directory of the examplebucket bucket.

    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 the error.html file to a local path.

    3. Upload the error.html file to the root directory of the examplebucket bucket. Set the ACL of the error.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.common.auth.*;
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";
        // 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. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";

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

        try {
            // Specify the name of the bucket. 
            SetBucketWebsiteRequest request = new SetBucketWebsiteRequest(bucketName);
            // Specify the default homepage of the static website that is hosted on the bucket. 
            request.setIndexDocument("index.html");
            // Specify the default 404 page of the static website that is 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;

// 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.  
$accessKeyId = getenv("OSS_ACCESS_KEY_ID"); 
$accessKeySecret = getenv("OSS_ACCESS_KEY_SECRET");
// 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 name of the bucket. Example: examplebucket. 
$bucket= "examplebucket";

// Set the default homepage to index.html and the default 404 page to error.html for the static website that is 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 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.ProviderAuth(EnvironmentVariableCredentialsProvider())
# 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, 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'))           
package main

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

func main() {
    // 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. 
    provider, err := oss.NewEnvironmentVariableCredentialsProvider()
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }

    // Create an OSSClient instance. 
    // 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. Specify your actual endpoint. 
    client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
    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. 
    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;

// 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. 
var endpoint = "yourEndpoint";
// 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. 
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket. 
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 that is 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 information about the account that is used to access OSS. */
    
    /* 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 name of the bucket. Example: examplebucket. */
    std::string BucketName = "examplebucket";

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

    ClientConfiguration conf;
    /* 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. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, 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;
        return -1;
    }

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

Use the OSS RESTful API

If your business requires a high level of customization, you can directly call the OSS RESTful API. To directly call an API operation, 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 it 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 tree, choose Data Management > Static Pages.
  2. In the Static Pages section, click Configure.
  3. Remove the configurations of the Default Homepage and Default 404 Page parameters and click Save.
    If the following page is displayed, the static website hosting feature is disabled. Disable static website hosting

What to do next