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 endpoint of the bucket to access the website.

Usage notes

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 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 have the subfolder homepage feature enabled, the object must also be stored in the subdirectory.

  • The default 404 page is the error page returned by OSS. When you use a browser to access the static website 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 access to 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 set object ACLs, see Configure ACL for objects.

When you access a static website hosted on a bucket by using the default endpoint of the bucket, the website is downloaded as a file to your computer. To preview a static website hosted on a bucket, you must map a custom domain name to the bucket and access the website by using the custom domain name. For more information about how to map a custom domain name to a bucket, see Map custom domain names.

Usage notes

For security reasons, starting from August 13, 2018 for regions inside mainland China, and September 25, 2019 for regions outside China, when you access web page objects whose MIME type is text/html and whose name extension is HTM, HTML, JSP, PLG, HTX, or STM by using browsers:
  • If you use the default endpoint of the bucket to access the objects, the following header is automatically contained in the response: Content-Disposition:'attachment=filename;'. In this case, the web page objects are downloaded as attachments. The content of the object cannot be previewed.
  • If you use a custom domain name mapped to the bucket to access the objects, the Content-Disposition:'attachment=filename;' header is not contained in the response. In this case, you can preview the object content if your browser supports preview of web page objects. For more information about how to map a custom domain name to a bucket, see Map custom domain names.

For more information, see Overview.

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 structure shows 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 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 a 302 status code and redirects the request to https://example.com/object/index.html. If object/index.html does not exist, OSS returns a 404 status code and https://example.com/error.html.
      • If Subfolder 404 Rule is set to NoSuchKey, OSS returns a 404 status code and https://example.com/error.html.
      • If Subfolder 404 Rule is set to Index, OSS continues to check whether the object/index.html object exists. If this object exists, OSS returns 200 and the content of this object. If the object does not exist, OSS returns https://example.com/error.html.

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 bucket on which you want to host a static website.
      3. In the left-side navigation pane, choose Basic Settings > Static Pages.
      4. In the Static Pages section, click Configure and set the parameters described in the following table. index1
        Parameter Description
        Default Homepage The default homepage that appears when you use a browser to access the static website hosted on the OSS bucket. In this example, set this parameter to index.html.
        Subfolder Homepage Specifies whether to enable the subfolder homepage feature for the bucket. In this example, select Disable. In that 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 when the object that you want to access does not exist in the bucket and a 404 error occurs. 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 the subfolder homepage feature 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 left-side navigation pane, click Buckets. On the Buckets page, click the name of the bucket on which you want to host the static website.
      2. In the left-side navigation pane, choose Basic Settings > Static Pages.
      3. In the Static Pages section, click Configure and set the parameters described in the following table. error
        Parameter Description
        Default Homepage The default homepage that appears when you use a browser to access the static website hosted on the OSS bucket. In this example, set this parameter to index.html.
        Subfolder Homepage Specifies whether to enable the subfolder homepage for the bucket. In this example, select Enable. After you enable the subfolder homepage feature 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 examplebucket, 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 this object exists, OSS returns 302 and redirects the request to https://examplebucket.oss-cn-hangzhou.aliyuncs.com/exampledir/index.html.
          • If this object does not exist, OSS returns 404 and checks whether the https://examplebucket.oss-cn-hangzhou.aliyuncs.com/error.html object exists. If this object does not exist either, OSS returns 404 status code.
        • NoSuckKey: OSS returns 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 this object exists, OSS returns 200 and the content of this 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 when the object that you want to access does not exist in the bucket and a 404 error occurs. 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.
      4. 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 the 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 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.

// In this example, the endpoint of the China (Hangzhou) region is used. Specify the endpoint based on your business requirements. 
String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// 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. 
String accessKeyId = "<yourAccessKeyId>";
String accessKeySecret = "<yourAccessKeySecret>";

// Create an OSSClient instance. 
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// Specify the bucket name. 
SetBucketWebsiteRequest request = new SetBucketWebsiteRequest("<yourBucketName>");
// Specify the default homepage for the static website hosted on the bucket. 
request.setIndexDocument("index.html");
// Specify the default 404 page for the static website hosted on the bucket. 
request.setErrorDocument("error.html");
ossClient.setBucketWebsite(request);

// Shut down the OSSClient instance. 
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;

// It is highly risky to log on with AccessKey of an Alibaba Cloud account because the account has permissions on all the APIs in OSS. We recommend that you log on as a RAM user to access APIs or perform routine operations and maintenance. To create a RAM account, log on to https://ram.console.aliyun.com.
$accessKeyId = "<yourAccessKeyId>";
$accessKeySecret = "<yourAccessKeySecret>";
// This example uses endpoint China (Hangzhou). Specify the actual endpoint based on your requirements.
$endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
$bucket= "<yourBucketName>";

// Configure static website hosting: The index paga is index.html and the error page is error.html.
$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

# Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to 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. 
auth = oss2.Auth('yourAccessKeyId', 'yourAccessKeySecret')
# In this example, the endpoint of the China (Hangzhou) region is used. Specify the endpoint based on your business requirements. For more information about the endpoints of other regions, see Regions and endpoints. 
# Specify the name of the bucket. Example: examplebucket. For more information about the naming conventions for buckets, see Bucket naming conventions. 
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;
var endpoint = "<yourEndpoint>";
var accessKeyId = "<yourAccessKeyId>";
var accessKeySecret = "<yourAccessKeySecret>";
var bucketName = "<yourBucketName>";
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try
{
    // Configure static website hosting.
    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 OSS account information. */
    std::string AccessKeyId = "yourAccessKeyId";
    std::string AccessKeySecret = "yourAccessKeySecret";
    std::string Endpoint = "yourEndpoint";
    std::string BucketName = "yourBucketName";
 
    /* Initialize network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    OssClient client(Endpoint, AccessKeyId, AccessKeySecret,  conf);
   
    /* Configure static website hosting. */
    SetBucketWebsiteRequest request(BucketName);
    request.setIndexDocument("index.html");
    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 network resources. */
    ShutdownSdk();
    return 0;
}

Use the RESTful API

If your program requires more custom options to configure static website hosting, you can call RESTful API operations. In that case, you must manually write code to calculate the signature. 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 pane, choose Basic Settings > Static Pages. In the Static Pages, click Configure.
  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