使用说明
配置静态网站托管时,您需要指定网站的默认首页和默认404页:
默认首页是您通过浏览器访问静态网站域名时,OSS返回的网站首页。
您为默认首页指定的文件必须是Bucket根目录下允许被匿名访问的文件。如果您还开通了子目录首页,则子目录下也应存在此文件。
默认404页是您通过浏览器访问Bucket内文件出现404错误时,OSS返回的错误页面。
您为默认404页指定的文件必须是Bucket根目录下允许被匿名访问的文件。
您可以通过将默认首页或者默认404页中指定文件的读写权限ACL设置为public-read
,确保该文件允许匿名访问。有关设置文件读写权限ACL的具体步骤,请参见文件ACL。
注意事项
出于安全考虑,中国内地各地域自2018年09月28日起,非中国内地各地域自2019年09月25日起,通过浏览器访问OSS静态网页类型文件(mimetype为text/html,扩展名包括HTM、HTML、JSP、PLG、HTX、STM):
费用说明
存储费用
按照存储静态网站文件(如HTML、CSS、JavaScript、图片等)占用的存储容量进行收费。更多信息,请参见存储费用。
流量费用
访问静态网站产生的流出流量,包括默认首页、图片、脚本等所有静态资源以及返回404错误页面所产生的流出流量。更多信息,请参见流量费用。
请求费用
向OSS发送GET请求访问默认首页、其他页面、静态资源以及404页面,这些请求会涉及GET类请求费用。更多信息,请参见请求费用。
配置示例
为Bucket开启静态网站托管后,您需要将与默认首页名称相同的文件(例如index.html)上传至目标Bucket,如果Bucket中包含了目录结构subdir/,则目录层级下也必须包含index.html文件。此外,您还需要将与默认404页名称相同的文件(例如error.html)上传至目标Bucket。Bucket的文件结构如下所示:
Bucket
├── index.html
├── error.html
├── example.txt
└── subdir/
└── index.html
如果该Bucket绑定了自定义域名example.com
,且配置的静态网站默认首页为index.html,默认404页为error.html。则通过自定义域名访问静态网站时,根据是否开通了子目录首页,访问规则如下:
未开通子目录首页
当您访问https://example.com/和https://example.com/subdir/时,OSS会返回https://example.com/index.html。
当您访问https://example.com/example.txt时,正常获取example.txt文件。
当您访问https://example.com/object时,因object不存在,OSS会返回https://example.com/error.html。
已开通子目录首页
当您访问https://example.com/时,OSS会返回https://example.com/index.html。
当您访问https://example.com/subdir/时,OSS会返回https://example.com/subdir/index.html。
当您访问https://example.com/example.txt时,正常获取example.txt文件。
当您访问https://example.com/object时,因object不存在,OSS会根据您设置的文件404规则返回对应信息:
如果文件404规则设置为Redirect(默认值),OSS会继续检查object/index.html是否存在。如果文件存在则返回302,并将访问请求重定向为https://example.com/object/index.html;如果文件不存在则返回404,并继续检查https://example.com/error.html。
如果文件404规则设置为NoSuchKey,则直接返回404,并继续检查https://example.com/error.html。
如果文件404规则设置为Index,OSS会继续检查object/index.html是否存在。如果文件存在则返回200,并直接返回文件内容。如果文件不存在,则继续检查https://example.com/error.html。
操作方式
使用OSS控制台
设置静态网站页面。
根据您的需求,选择是否开通子目录首页。
创建并上传默认首页。
当您为examplebucket配置静态网站托管时指定的默认首页为index.html,您需要将与默认首页名称相同的文件上传至examplebucket根目录下。由于examplebucket中包含了子目录subdir/,则子目录subdir/下也必须包含index.html文件。
创建index.html文件。index.html文件配置示例如下:
<html>
<head>
<title>My Website Home Page</title>
<meta charset="utf-8">
</head>
<body>
<p>Now hosted on OSS.</p>
</body>
</html>
将index.html文件保存至本地路径。
分别将index.html文件上传至examplebucket根目录以及子目录subdir下。上传文件时,您需要将文件读写权限设置为公共读。
关于上传文件的具体操作,请参见简单上传。
创建并上传默认404页。
当您为examplebucket配置静态网站托管时指定的默认404页为error.html,您需要将与默认404页名称相同的文件上传至examplebucket根目录下。
创建error.html文件。error.html文件配置示例如下:
<html>
<head>
<title>Hello OSS!</title>
<meta charset="utf-8">
</head>
<body>
<p>This is error 404 page.</p>
</body>
</html>
将error.html文件保存至本地。
将error.html文件上传至examplebucket根目录下。上传文件时,您需要将文件读写权限设置为公共读。
使用阿里云SDK
以下仅列举常见SDK的设置静态网站托管的代码示例。关于其他SDK的设置静态网站托管的代码示例,请参见SDK简介。
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 {
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
String bucketName = "examplebucket";
String region = "cn-hangzhou";
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
SetBucketWebsiteRequest request = new SetBucketWebsiteRequest(bucketName);
request.setIndexDocument("index.html");
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\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\CoreOssException;
use OSS\Model\WebsiteConfig;
$provider = new EnvironmentVariableCredentialsProvider();
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
$bucket= "examplebucket";
$websiteConfig = new WebsiteConfig("index.html", "error.html");
try {
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
"region"=> "cn-hangzhou"
);
$ossClient = new OssClient($config);
$ossClient->putBucketWebsite($bucket, $websiteConfig);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
import oss2
from oss2.models import BucketWebsite
from oss2.credentials import EnvironmentVariableCredentialsProvider
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
region = "cn-hangzhou"
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)
bucket.put_bucket_website(BucketWebsite('index.html', 'error.html'))
package main
import (
"fmt"
"os"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New("yourEndpoint", "", "", clientOptions...)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
bucketName := "examplebucket"
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 = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
var bucketName = "examplebucket";
const string region = "cn-hangzhou";
var conf = new ClientConfiguration();
conf.SignatureVersion = SignatureVersion.V4;
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
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)
{
std::string Endpoint = "yourEndpoint";
std::string Region = "yourRegion";
std::string BucketName = "examplebucket";
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
SetBucketWebsiteRequest request(BucketName);
request.setIndexDocument("index.html");
request.setErrorDocument("error.html");
auto outcome = client.SetBucketWebsite(request);
if (!outcome.isSuccess()) {
std::cout << "SetBucketWebsite fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
ShutdownSdk();
return 0;
}
使用命令行工具ossutil
您可以使用命令行工具ossutil来设置静态网站托管,ossutil的安装请参见安装ossutil。
以下命令用于配置存储空间examplebucket
的网站托管选项。
ossutil api put-bucket-website --bucket examplebucket --website-configuration "{\"IndexDocument\":{\"Suffix\":\"index.html\",\"SupportSubDir\":\"true\",\"Type\":\"0\"},\"ErrorDocument\":{\"Key\":\"error.html\",\"HttpStatus\":\"404\"},\"RoutingRules\":{\"RoutingRule\":[{\"RuleNumber\":\"1\",\"Condition\":{\"KeyPrefixEquals\":\"abc/\",\"HttpErrorCodeReturnedEquals\":\"404\"},\"Redirect\":{\"RedirectType\":\"Mirror\",\"PassQueryString\":\"true\",\"MirrorURL\":\"http://example.com/\",\"MirrorPassQueryString\":\"true\",\"MirrorFollowRedirect\":\"true\",\"MirrorCheckMd5\":\"false\",\"MirrorHeaders\":{\"PassAll\":\"true\",\"Pass\":[\"myheader-key1\",\"myheader-key2\"],\"Remove\":[\"myheader-key3\",\"myheader-key4\"],\"Set\":{\"Key\":\"myheader-key5\",\"Value\":\"myheader-value5\"}}}},{\"RuleNumber\":\"2\",\"Condition\":{\"KeyPrefixEquals\":\"abc/\",\"HttpErrorCodeReturnedEquals\":\"404\",\"IncludeHeader\":{\"Key\":\"host\",\"Equals\":\"test.oss-cn-beijing-internal.aliyuncs.com\"}},\"Redirect\":{\"RedirectType\":\"AliCDN\",\"Protocol\":\"http\",\"HostName\":\"example.com\",\"PassQueryString\":\"false\",\"ReplaceKeyWith\":\"prefix/${key}.suffix\",\"HttpRedirectCode\":\"301\"}},{\"Condition\":{\"HttpErrorCodeReturnedEquals\":\"404\"},\"RuleNumber\":\"3\",\"Redirect\":{\"ReplaceKeyWith\":\"prefix/${key}\",\"HttpRedirectCode\":\"302\",\"EnableReplacePrefix\":\"false\",\"PassQueryString\":\"false\",\"Protocol\":\"http\",\"HostName\":\"example.com\",\"RedirectType\":\"External\"}}]}}"
关于该命令的更多信息,请参见put-bucket-website。
相关API
以上操作方式底层基于API实现,如果您的程序自定义要求较高,您可以直接发起REST API请求。直接发起REST API请求需要手动编写代码计算签名。更多信息,请参见PutBucketWebsite。
常见问题
开启静态网站托管功能后是否支持关闭?
当您不再需要使用默认首页、默认404页等静态网站托管配置时,请按如下步骤关闭静态网站托管功能:
- 在左侧导航栏,选择。
- 在静态页面区域,单击设置。
- 清空默认首页和默认404页配置,然后单击保存。
返回如下页面,表示已成功关闭静态网站托管功能。
