文档

Java静态网站托管(镜像回源)

更新时间:

您可以将存储空间(Bucket)设置为静态网站托管模式并设置镜像回源的跳转规则(RoutingRule)。静态网站托管模式配置生效后,访问网站相当于访问Bucket,并且能够自动跳转至指定的索引页面和错误页面。镜像回源的跳转规则配置生效后,可用于数据无缝迁移到OSS的场景。

注意事项

  • 本文以华东1(杭州)外网Endpoint为例。如果您希望通过与OSS同地域的其他阿里云产品访问OSS,请使用内网Endpoint。关于OSS支持的Region与Endpoint的对应关系,请参见访问域名和数据中心

  • 本文以从环境变量读取访问凭证为例。如何配置访问凭证,请参见Java配置访问凭证

  • 本文以OSS域名新建OSSClient为例。如果您希望通过自定义域名、STS等方式新建OSSClient,请参见新建OSSClient

  • 要设置静态网站托管或者镜像回源,您必须有oss:PutBucketWebsite权限;要获取静态网站托管或者镜像回源,您必须有oss:GetBucketWebsite权限;要删除静态网站托管或者镜像回源,您必须有oss:DeleteBucketWebsite权限。具体操作,请参见为RAM用户授权自定义的权限策略

静态网站托管

  • 设置静态网站托管

    以下代码用于设置静态网站托管:

    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 {
            // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // 填写Bucket名称,例如examplebucket。
            String bucketName = "examplebucket";
    
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
    
            try {
                // 填写Bucket名称。
                SetBucketWebsiteRequest request = new SetBucketWebsiteRequest(bucketName);
                // 设置静态网站托管的默认主页。
                request.setIndexDocument("index.html");
                // 设置静态网站托管的默认404页。
                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();
                }
            }
        }
    }
  • 查看静态网站托管配置

    以下代码用于查看静态网站托管配置:

    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.BucketWebsiteResult;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // 填写Bucket名称,例如examplebucket。
            String bucketName = "examplebucket";
    
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
    
            try {
                // 填写Bucket名称。
                BucketWebsiteResult result = ossClient.getBucketWebsite(bucketName);
                // 查看静态网站托管配置的默认首页和默认404页。
                System.out.println(result.getIndexDocument());
                System.out.println(result.getErrorDocument());
            } 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();
                }
            }
        }
    }
  • 删除静态网站托管配置

    以下代码用于删除静态网站托管配置:

    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;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // 填写Bucket名称,例如examplebucket。
            String bucketName = "examplebucket";
    
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
    
            try {
                // 填写Bucket名称。
                ossClient.deleteBucketWebsite(bucketName);
            } 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();
                }
            }
        }
    }

镜像回源

镜像回源主要用于数据无缝迁移到OSS的场景。例如某服务已经在用户建立的源站或者在其他云产品上运行,现因业务发展,需要将服务迁移至OSS,迁移时需保证服务的正常运行。您可以在迁移过程中使用镜像回源规则获取未迁移至OSS的部分数据,保证服务的正常运行。

  • 设置镜像回源

    例如,当请求者访问目标Bucket中不存在的文件时,可以通过指定回源条件和回源地址,从源站中获取目标文件。例如您在华东1(杭州)有名为examplebucket的Bucket,您希望请求者访问Bucket根目录下examplefolder目录中不存在的文件时,可以从https://www.example.com/站点的examplefolder目录获取目标文件。

    以下代码用于设置符合上述场景的镜像回源规则:

    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 {
            // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // 填写Bucket名称,例如examplebucket。
            String bucketName = "examplebucket";
    
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
    
            try {
                SetBucketWebsiteRequest request = new SetBucketWebsiteRequest(bucketName);
                // 设置默认主页后,访问以非正斜线(/)结尾的Object,且该Object不存在时的行为。
                //request.setSubDirType(null);
                // 指定访问子目录时,是否支持转到子目录下的默认主页。
                //request.setSupportSubDir(false);
    
                List<RoutingRule> routingRules = new ArrayList<RoutingRule>();
    
                RoutingRule rule = new RoutingRule();
                rule.setNumber(1);
                // 只有匹配此前缀的Object才能匹配此规则。
                rule.getCondition().setKeyPrefixEquals("examplebucket");
                // 访问指定Object时,返回status 404才能匹配此规则。
                rule.getCondition().setHttpErrorCodeReturnedEquals(404);
                // 指定跳转的类型。
                rule.getRedirect().setRedirectType(RoutingRule.RedirectType.Mirror);
                // 指定镜像回源的源站地址。例如https://www.example.com/。
                rule.getRedirect().setMirrorURL("<yourMirrorURL>");
                //rule.getRedirect().setMirrorRole("AliyunOSSMirrorDefaultRole");
                // 指定执行跳转或者镜像回源规则时,是否携带请求参数。
                rule.getRedirect().setPassQueryString(true);
                // 与PassQueryString作用相同,优先级高于PassQueryString。只有设置RedirectType为Mirror时生效。
                rule.getRedirect().setMirrorPassQueryString(true);
                // 指定跳转时返回的状态码。只有设置RedirectType为External或者AliCDN时生效。
                //rule.getRedirect().setHttpRedirectCode(302);
                // 指定跳转时的域名,域名需符合域名规范。
                //rule.getRedirect().setHostName("oss.aliyuncs.com");
                // 指定跳转时的协议。只有设置RedirectType为External或者AliCDN时才生效。
                //rule.getRedirect().setProtocol(RoutingRule.Protocol.Https);
                // Redirect时Object名称将替换成ReplaceKeyWith指定的值,ReplaceKeyWith支持设置变量。
                //rule.getRedirect().setReplaceKeyWith("${key}.jpg");
                // 如果设置此字段为true,则Object的前缀将被替换为ReplaceKeyPrefixWith指定的值。
                rule.getRedirect().setEnableReplacePrefix(true);
                // Redirect时Object名称的前缀将替换成该值。
                rule.getRedirect().setReplaceKeyPrefixWith("examplebucket");
                // 是否检查回源body的MD5。只有设置RedirectType为Mirror时生效。
                rule.getRedirect().setMirrorCheckMd5(true);
    
                RoutingRule.MirrorHeaders mirrorHeaders = new RoutingRule.MirrorHeaders();
                // 是否透传除以下Header之外的其他Header到源站。只有设置RedirectType为Mirror时生效。
                mirrorHeaders.setPassAll(false);
                List passes = new ArrayList<String>();
                passes.add("cache-control");
                // 透传指定的Header到源站。只有设置RedirectType为Mirror时生效。
                mirrorHeaders.setPass(passes);
                List removes = new ArrayList<String>();
                removes.add("content-type");
                // 禁止透传指定的Header到源站。只有设置RedirectType为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);
                // 设置传到源站的Header。不管请求中是否携带这些指定的Header,回源时都会设置这些Header。
                mirrorHeaders.setSet(sets);
                // 指定回源时携带的Header。只有设置RedirectType为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();
                }
            }
        }
    }
  • 获取镜像回源配置

    以下代码用于获取镜像回源配置:

    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.BucketWebsiteResult;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // 填写Bucket名称,例如examplebucket。
            String bucketName = "examplebucket";
    
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
    
            try {
                BucketWebsiteResult result = ossClient.getBucketWebsite(bucketName);
                result.getSubDirType();
                // 获取匹配并执行跳转规则或者镜像回源规则的序号。
                System.out.println(result.getRoutingRules().get(0).getNumber());
                // 获取规则匹配的前缀。
                System.out.println(result.getRoutingRules().get(0).getCondition().getKeyPrefixEquals());
                // 获取HTTP状态码。
                System.out.println(result.getRoutingRules().get(0).getCondition().getHttpErrorCodeReturnedEquals());
                // 获取规则匹配的后缀。
                System.out.println(result.getRoutingRules().get(0).getCondition().getKeySuffixEquals());
                // 获取跳转类型。
                System.out.println(result.getRoutingRules().get(0).getRedirect().getRedirectType());
                // 获取携带的请求参数。
                System.out.println(result.getRoutingRules().get(0).getRedirect().getMirrorPassQueryString());
                // 获取镜像回源的源站地址。
                System.out.println(result.getRoutingRules().get(0).getRedirect().getMirrorURL());
                // 获取跳转时返回的状态码。
                System.out.println(result.getRoutingRules().get(0).getRedirect().getHttpRedirectCode());
                // 获取透传指定的Header。
                System.out.println(result.getRoutingRules().get(0).getRedirect().getMirrorHeaders().getPass().get(0));
                // 获取禁止透传指定的Header。
                System.out.println(result.getRoutingRules().get(0).getRedirect().getMirrorHeaders().getRemove().get(0));
                // 获取跳转时的协议。
                System.out.println(result.getRoutingRules().get(0).getRedirect().getProtocol());
                // 获取跳转时的域名。
                System.out.println(result.getRoutingRules().get(0).getRedirect().getHostName());
                // 获取Redirect时Object名称的前缀替换值。如果前缀为空,则将这个字符串插入Object名称的前面。
                System.out.println(result.getRoutingRules().get(0).getRedirect().getReplaceKeyPrefixWith());
                // 获取Redirect时Object名称通过ReplaceKeyWith指定的替换值,ReplaceKeyWith支持变量。
                System.out.println(result.getRoutingRules().get(0).getRedirect().getReplaceKeyWith());
                // 获取跳转时返回的状态码。
                System.out.println(result.getRoutingRules().get(0).getRedirect().getHttpRedirectCode());
            } 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();
                }
            }
        }
    }
  • 删除镜像回源配置

    以下代码用于删除镜像回源配置:

    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;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // 填写Bucket名称,例如examplebucket。
            String bucketName = "examplebucket";
    
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
    
            try {
                // 填写Bucket名称。
                ossClient.deleteBucketWebsite(bucketName);
            } 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();
                }
            }
        }
    }

相关文档

  • 关于静态网站托管以及镜像回源的完整示例代码,请参见GitHub示例

  • 关于设置静态网站托管或者镜像回源的API接口说明,请参见PutBucketWebsite

  • 关于获取静态网站托管或者镜像回源的API接口说明,请参见GetBucketWebsite

  • 关于删除静态网站托管或者镜像回源的API接口说明,请参见DeleteBucketWebsite

  • 本页导读 (1)
文档反馈