全部產品
Search
文件中心

Object Storage Service:Java靜態網站託管(鏡像回源)

更新時間:Oct 25, 2024

您可以將儲存空間(Bucket)設定為靜態網站託管模式並設定鏡像回源的跳轉規則(RoutingRule)。靜態網站託管模式配置生效後,訪問網站相當於訪問Bucket,並且能夠自動跳轉至指定的索引頁面和錯誤頁面。鏡像回源的跳轉規則配置生效後,可用於資料無縫遷移到OSS的情境。

注意事項

  • 本文以華東1(杭州)外網Endpoint為例。如果您希望通過與OSS同地區的其他阿里雲產品訪問OSS,請使用內網Endpoint。關於OSS支援的Region與Endpoint的對應關係,請參見OSS訪問網域名稱、資料中心、開放連接埠

  • 本文以從環境變數讀取存取憑證為例。如何配置訪問憑證,請參見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";
            // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
            String region = "cn-hangzhou";
    
            // 建立OSSClient執行個體。
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            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";
            // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
            String region = "cn-hangzhou";
    
            // 建立OSSClient執行個體。
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            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";
            // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
            String region = "cn-hangzhou";
    
            // 建立OSSClient執行個體。
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            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";
            // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
            String region = "cn-hangzhou";
    
            // 建立OSSClient執行個體。
            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);
                // 設定預設首頁後,訪問以非正斜線(/)結尾的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";
            // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
            String region = "cn-hangzhou";
    
            // 建立OSSClient執行個體。
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            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";        
            // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
            String region = "cn-hangzhou";
    
            // 建立OSSClient執行個體。
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            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