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.RoutingRule;
import com.aliyun.oss.model.SetBucketWebsiteRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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 {
SetBucketWebsiteRequest request = new SetBucketWebsiteRequest(bucketName);
// Specify the operation that you want to perform if the default homepage is specified, the name of the requested object does not end with a forward slash (/), and the object does not exist.
//request.setSubDirType(null);
// Specify whether to redirect the requester to the default homepage in the subdirectory when the subdirectory is accessed.
//request.setSupportSubDir(false);
List<RoutingRule> routingRules = new ArrayList<RoutingRule>();
RoutingRule rule = new RoutingRule();
rule.setNumber(1);
// Specify the prefix that is contained in the object names. Only the objects whose names contain the specified prefix match the rule.
rule.getCondition().setKeyPrefixEquals("examplebucket");
// Specify the HTTP status code. The rule is matched only when the specified object is accessed and HTTP status code 404 is returned.
rule.getCondition().setHttpErrorCodeReturnedEquals(404);
// Specify the redirection type.
rule.getRedirect().setRedirectType(RoutingRule.RedirectType.Mirror);
// Specify the URL of the origin for the mirroring-based back-to-origin rule. Example: https://www.example.com/.
rule.getRedirect().setMirrorURL("<yourMirrorURL>");
//rule.getRedirect().setMirrorRole("AliyunOSSMirrorDefaultRole");
// Specify whether to include the request parameters when the redirection rule or the mirroring-based back-to-origin rule is executed.
rule.getRedirect().setPassQueryString(true);
// This parameter is used in the same manner as the PassQueryString parameter and is assigned a higher priority level than the PassQueryString parameter. This parameter takes effect only when you set the RedirectType parameter to Mirror.
rule.getRedirect().setMirrorPassQueryString(true);
// Specify the HTTP status code in the response when the request is redirected. This parameter takes effect only when you set the RedirectType parameter to External or AliCDN.
//rule.getRedirect().setHttpRedirectCode(302);
// Specify the domain name that you want to use for redirection. The domain name must comply with the naming conventions for domain names.
//rule.getRedirect().setHostName("oss.aliyuncs.com");
// Specify the protocol that you want to use for redirection. This parameter takes effect only when you set the RedirectType parameter to External or AliCDN.
//rule.getRedirect().setProtocol(RoutingRule.Protocol.Https);
// Specify the string that you want to use to replace the object name when the request is redirected. You can set this parameter to a variable.
//rule.getRedirect().setReplaceKeyWith("${key}.jpg");
// If you set this parameter to true, the prefix of the object name is replaced with the value specified by the ReplaceKeyPrefixWith parameter.
rule.getRedirect().setEnableReplacePrefix(true);
// Specify the string that you want to use to replace the prefix of the object name during redirection.
rule.getRedirect().setReplaceKeyPrefixWith("examplebucket");
// Specify whether to check the MD5 hash of the response body that is returned by the origin. This parameter takes effect only when you set the RedirectType parameter to Mirror.
rule.getRedirect().setMirrorCheckMd5(true);
RoutingRule.MirrorHeaders mirrorHeaders = new RoutingRule.MirrorHeaders();
// Specify whether to pass through all request headers except the following header to the origin. This parameter takes effect only when you set the RedirectType parameter to Mirror.
mirrorHeaders.setPassAll(false);
List passes = new ArrayList<String>();
passes.add("cache-control");
// Specify the headers that you want to pass through to the origin. This parameter takes effect only when you set the RedirectType parameter to Mirror.
mirrorHeaders.setPass(passes);
List removes = new ArrayList<String>();
removes.add("content-type");
// Specify the headers that you do not want to pass through to the origin. This parameter takes effect only when you set the RedirectType parameter to Mirror.
mirrorHeaders.setRemove(removes);
List sets = new ArrayList<Map<String, String>>();
Map header1 = new HashMap<String, String>();
header1.put("Key", "key1");
header1.put("Value", "value1");
Map header2 = new HashMap<String, String>();
header2.put("Key", "key2");
header2.put("Value", "value2");
sets.add(header1);
sets.add(header2);
// Specify the headers that you want to pass through to the origin. The specified headers are passed through to the origin regardless of whether the headers are included in the request.
mirrorHeaders.setSet(sets);
// Specify the headers that you want to include in the response when the requested object is obtained from the origin. This parameter takes effect only when you set the RedirectType parameter to Mirror.
rule.getRedirect().setMirrorHeaders(mirrorHeaders);
routingRules.add(rule);
request.setRoutingRules(routingRules);
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();
}
}
}
}
#-*-coding:utf-8-*-
import oss2
from oss2.models import BucketWebsite, MirrorHeadersSet, RedirectMirrorHeaders, Redirect, RoutingRule, \
REDIRECT_TYPE_MIRROR, Condition
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.
index_file = 'index.html'
error_file = 'error.html'
# Specify the match conditions.
condition1 = Condition(key_prefix_equals='examplefolder',
http_err_code_return_equals=404)
# Specify the headers that you want to include in the request when you use mirroring-based back-to-origin.
mirror_headers_set_1 = MirrorHeadersSet("myheader-key5","myheader-value5")
mirror_headers_set_2 = MirrorHeadersSet("myheader-key6","myheader-value6")
set_list = [mirror_headers_set_1, mirror_headers_set_2]
pass_list = ['myheader-key1', 'myheader-key2']
remove_list = ['myheader-key3', 'myheader-key4']
mirror_header = RedirectMirrorHeaders(pass_all=True, pass_list=pass_list, remove_list=remove_list, set_list=set_list)
# Specify the operation to perform after the rule is matched.
redirect1 = Redirect(redirect_type=REDIRECT_TYPE_MIRROR, mirror_url='https://www.example.com/',
mirror_pass_query_string=True, mirror_follow_redirect=True, mirror_check_md5=True, mirror_headers=mirror_header)
rule1 = RoutingRule(rule_num=1, condition=condition1, redirect=redirect1)
website_set = BucketWebsite(index_file, error_file, [rule1])
# Configure mirroring-based back-to-origin.
bucket.put_bucket_website(website_set)
package main
import (
"fmt"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"os"
)
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"
var indexWebsite = "myindex.html"
var errorWebsite = "myerror.html"
btrue := true
bfalse := false
// Set the back-to-origin type to mirroring-based back-to-origin.
ruleOk := oss.RoutingRule{
RuleNumber: 1,
Condition: oss.Condition{
KeyPrefixEquals: "",
// Set the back-to-origin condition to HTTP status code 404.
HTTPErrorCodeReturnedEquals: 404,
},
Redirect: oss.Redirect{
RedirectType: "Mirror",
// PassQueryString: &btrue,
// Specify the back-to-origin URL for a mirroring-based back-to-origin rule.
MirrorURL: "http://www.test.com/",
// MirrorPassQueryString:&btrue,
// MirrorFollowRedirect:&bfalse,
// MirrorCheckMd5:&bfalse,
MirrorHeaders: oss.MirrorHeaders{
// PassAll:&bfalse,
// Transmit specific HTTP headers.
Pass: []string{"myheader-key1", "myheader-key2"},
// Prohibit the transmission of specific HTTP headers.
Remove: []string{"myheader-key3", "myheader-key4"},
Set: []oss.MirrorHeaderSet{
{
Key: "myheader-key5",
Value: "myheader-value5",
},
},
},
},
}
// Set the back-to-origin type to redirection-based back-to-origin.
ruleArrOk := []oss.RoutingRule{
{
RuleNumber: 2,
Condition: oss.Condition{
// Set the back-to-origin condition to HTTP status code 404 and the prefix in object names to abc/.
KeyPrefixEquals: "abc/",
HTTPErrorCodeReturnedEquals: 404,
IncludeHeader: []oss.IncludeHeader{
{
Key: "host",
Equals: "test.oss-cn-beijing-internal.aliyuncs.com",
},
},
},
Redirect: oss.Redirect{
RedirectType: "AliCDN",
Protocol: "http",
HostName: "www.test.com",
PassQueryString: &bfalse,
ReplaceKeyWith: "prefix/${key}.suffix",
HttpRedirectCode: 301,
},
},
// Set the back-to-origin type to mirroring-based back-to-origin.
{
RuleNumber: 3,
Condition: oss.Condition{
KeyPrefixEquals: "",
HTTPErrorCodeReturnedEquals: 404,
},
Redirect: oss.Redirect{
RedirectType: "Mirror",
PassQueryString: &btrue,
MirrorURL: "http://www.test.com/",
MirrorPassQueryString: &btrue,
MirrorFollowRedirect: &bfalse,
MirrorCheckMd5: &bfalse,
MirrorHeaders: oss.MirrorHeaders{
PassAll: &btrue,
Pass: []string{"myheader-key1", "myheader-key2"},
Remove: []string{"myheader-key3", "myheader-key4"},
Set: []oss.MirrorHeaderSet{
{
Key: "myheader-key5",
Value: "myheader-value5",
},
},
},
},
},
}
wxmlOne := oss.WebsiteXML{
IndexDocument: oss.IndexDocument{
Suffix: indexWebsite,
},
ErrorDocument: oss.ErrorDocument{
Key: errorWebsite,
},
}
wxmlOne.RoutingRules = append(wxmlOne.RoutingRules, ruleOk)
wxmlOne.RoutingRules = append(wxmlOne.RoutingRules, ruleArrOk...)
err = client.SetBucketWebsiteDetail(bucketName, wxmlOne)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
}