バケットの静的Webサイトホスティングを有効にし、ミラーリングベースのback-to-originルールを設定できます。 バケットで静的Webサイトをホストした後、バケットにアクセスしてWebサイトにアクセスできます。 指定したインデックスページまたはエラーページに自動的にリダイレクトされます。 ミラーリングベースのback-to-originルールを設定して有効にすると、ミラーリングベースのback-to-originを使用して、データをObject Storage Service (OSS) にシームレスに移行できます。
使用上の注意
このトピックでは、中国 (杭州) リージョンのパブリックエンドポイントを使用します。 OSSと同じリージョンにある他のAlibaba CloudサービスからOSSにアクセスする場合は、内部エンドポイントを使用します。 OSSリージョンとエンドポイントの詳細については、「リージョン、エンドポイント、オープンポート」をご参照ください。
このトピックでは、アクセス資格情報は環境変数から取得します。 アクセス資格情報の設定方法の詳細については、「アクセス資格情報の設定」をご参照ください。
このトピックでは、OSSエンドポイントを使用してOSSClientインスタンスを作成します。 カスタムドメイン名またはSecurity Token Service (STS) を使用してOSSClientインスタンスを作成する場合は、「OSSClientインスタンスの作成」をご参照ください。
静的Webサイトホスティングまたはミラーリングベースのback-To-originを構成するには、
oss:PutBucketWebsite
権限が必要です。 静的Webサイトホスティング構成またはミラーリングベースのback-To-originルールを照会するには、oss:GetBucketWebsite
権限が必要です。 静的Webサイトホスティング設定またはミラーリングベースのback-To-originルールを削除するには、oss:DeleteBucketWebsite
権限が必要です。 詳細については、「RAMポリシーの一般的な例」をご参照ください。
静的 Web サイトホスティング
静的 Web サイトホスティングの設定
次のサンプルコードは、静的Webサイトホスティングを構成する方法の例を示しています。
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 { // 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"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { // Specify the name of the bucket. SetBucketWebsiteRequest request = new SetBucketWebsiteRequest(bucketName); // Specify the default homepage of the static website that is hosted on the bucket. request.setIndexDocument("index.html"); // Specify the default 404 page of the static website that is hosted on the bucket. 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(); } } } }
静的Webサイトホスティング設定の照会
次のコードは、静的Webサイトホスティング設定を照会する方法の例を示しています。
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 { // 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"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { // Specify the name of the bucket. BucketWebsiteResult result = ossClient.getBucketWebsite(bucketName); // Query the default homepage and default 404 page of the static website hosted on the bucket. 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(); } } } }
静的 Web サイトホスティング設定の削除
次のサンプルコードは、静的Webサイトホスティング設定を削除する方法の例を示しています。
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 { // 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"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { // Specify the name of the 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(); } } } }
ミラーリングベースのback-to-origin
ミラーリングベースのback-to-originを使用すると、データをOSSにシームレスに移行できます。 たとえば、サービスを中断することなく、自己管理オリジンまたは別のクラウドサービスからOSSにサービスを移行できます。 移行中にミラーリングベースのback-to-originルールを使用して、OSSに移行されていないデータを取得できます。 これにより、ビジネスの継続性が確保されます。
ミラーリングベースのback-to-originの設定
要求者が特定のバケット内のオブジェクトにアクセスしようとしても、そのオブジェクトが存在しない場合は、オリジンおよびback-to-origin条件でオブジェクトのURLを指定して、要求者がオリジンからオブジェクトを取得できるようにすることができます。 たとえば、examplebucketという名前のバケットは、中国 (杭州) リージョンにあります。 リクエスタがバケットのルートディレクトリのexamplefolderディレクトリにあるオブジェクトにアクセスしようとしたが、そのオブジェクトが存在しない場合、リクエスタはそのオリジンにリダイレクトされ、https://www.example.com/ オリジンのexamplefolderディレクトリに格納されている必要なオブジェクトにアクセスします。
次のサンプルコードは、前述のシナリオのミラーリングベースのback-to-originルールを設定する方法の例を示しています。
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"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. 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); // 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(); } } } }
ミラーリングベースのback-to-origin設定の照会
次のコードでは、ミラーリングベースのback-to-origin構成を照会する方法の例を示します。
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 { // 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"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. 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(); // Query the sequence number that is used to match and run redirection rules or mirroring-based back-to-origin rules. System.out.println(result.getRoutingRules().get(0).getNumber()); // Query the prefix that is used for rule matching. System.out.println(result.getRoutingRules().get(0).getCondition().getKeyPrefixEquals()); // Query the HTTP status code. System.out.println(result.getRoutingRules().get(0).getCondition().getHttpErrorCodeReturnedEquals()); // Query the suffix that is used for rule matching. System.out.println(result.getRoutingRules().get(0).getCondition().getKeySuffixEquals()); // Query the redirection type. System.out.println(result.getRoutingRules().get(0).getRedirect().getRedirectType()); // Query the parameters in the request. System.out.println(result.getRoutingRules().get(0).getRedirect().getMirrorPassQueryString()); // Query the URL of the origin for mirroring-based back-to-origin. System.out.println(result.getRoutingRules().get(0).getRedirect().getMirrorURL()); // Query the HTTP status code in the response. System.out.println(result.getRoutingRules().get(0).getRedirect().getHttpRedirectCode()); // Query the headers that can be passed through. System.out.println(result.getRoutingRules().get(0).getRedirect().getMirrorHeaders().getPass().get(0)); // Query the headers that cannot be passed through. System.out.println(result.getRoutingRules().get(0).getRedirect().getMirrorHeaders().getRemove().get(0)); // Query the protocol that is used for redirection. System.out.println(result.getRoutingRules().get(0).getRedirect().getProtocol()); // Query the domain name to which the request is redirected. System.out.println(result.getRoutingRules().get(0).getRedirect().getHostName()); // Specify the string that is used to replace the prefix of the object name when the request is redirected. If the prefix of an object is empty, this string precedes the object name. System.out.println(result.getRoutingRules().get(0).getRedirect().getReplaceKeyPrefixWith()); // Specify the string that is used to replace the object name when the request is redirected. This parameter can be set to a variable. System.out.println(result.getRoutingRules().get(0).getRedirect().getReplaceKeyWith()); // Query the HTTP status code in the response. 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(); } } } }
ミラーリングベースのback-to-origin設定の削除
次のサンプルコードは、ミラーリングベースのback-to-origin設定を削除する方法の例を示しています。
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 { // 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"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { // Specify the name of the 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(); } } } }
関連ドキュメント
静的Webサイトホスティングとミラーリングベースのback-to-originを設定するために使用される完全なサンプルコードについては、GitHubをご覧ください。
静的Webサイトホスティングまたはミラーリングベースのback-to-originを構成するために呼び出すことができるAPI操作の詳細については、「PutBucketWebsite」をご参照ください。
静的Webサイトホスティング構成またはミラーリングベースのback-to-originルールを照会するために呼び出すことができるAPI操作の詳細については、「GetBucketWebsite」をご参照ください。
静的Webサイトホスティング設定またはミラーリングベースのback-to-originルールを削除するために呼び出すことができるAPI操作の詳細については、「DeleteBucketWebsite」をご参照ください。