All Products
Search
Document Center

Object Storage Service:Static website hosting (mirroring-based back-to-origin)

Last Updated:Sep 04, 2023

You can enable static website hosting for buckets and configure mirroring-based back-to-origin rules. After you host a static website on a bucket, you can access the bucket to visit the website. You are automatically redirected to the specified index page or error page. After mirroring-based back-to-origin rules are configured and take effect, you can use mirroring-based back-to-origin to seamlessly migrate data to Object Storage Service (OSS).

Usage notes

  • In this topic, the public endpoint of the China (Hangzhou) region is used. If you want to access OSS by using other Alibaba Cloud services in the same region as OSS, use an internal endpoint. For more information about the regions and endpoints supported by OSS, see Regions and endpoints.

  • In this topic, access credentials are obtained from environment variables. For more information about how to configure access credentials, see Configure access credentials.

  • In this topic, an OSSClient instance is created by using an OSS endpoint. If you want to create an OSSClient instance by using custom domain names or Security Token Service (STS), see Create an OSSClient instance.

  • To configure static website hosting or mirroring-based back-to-origin, you must have the oss:PutBucketWebsite permission. To query static website hosting configurations or mirroring-based back-to-origin rules, you must have the oss:GetBucketWebsite permission. To delete static website hosting configurations or mirroring-based back-to-origin rules, you must have the oss:DeleteBucketWebsite permission. For more information, see Common examples of RAM policies.

Static website hosting

  • Configure static website hosting

    The following sample code provides an example on how to configure static website hosting:

    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";
    
            // Create an OSSClient instance. 
            OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
    
            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();
                }
            }
        }
    }
  • Query static website hosting configurations

    The following code provides an example on how to query the static website hosting configurations:

    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";
    
            // Create an OSSClient instance. 
            OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
    
            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();
                }
            }
        }
    }
  • Delete static website hosting configurations

    The following sample code provides an example on how to delete the static website hosting configurations:

    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";
    
            // Create an OSSClient instance. 
            OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
    
            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();
                }
            }
        }
    }

Mirroring-based back-to-origin

Mirroring-based back-to-origin allows you to seamlessly migrate data to OSS. For example, you can migrate services from a self-managed origin or from another cloud service to OSS without causing a service interruption. You can use mirroring-based back-to-origin rules during migration to obtain data that is not migrated to OSS. This ensures business continuity.

  • Configure mirroring-based back-to-origin

    If a requester attempts to access an object in a specific bucket and the object does not exist, you can specify the URL of the object in the origin and back-to-origin conditions to allow the requester to obtain the object from the origin. For example, a bucket named examplebucket is located in the China (Hangzhou) region. When a requester attempts to access an object in the examplefolder directory of the root directory of the bucket but the object does not exist, the requester is redirected to its origin https://www.example.com/ to access the required object that is stored in the examplefolder directory of the origin.

    The following sample code provides an example on how to configure mirroring-based back-to-origin rules for the preceding scenario:

    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();
                }
            }
        }
    }
  • Query the mirroring-based back-to-origin configurations

    The following code provides an example on how to query the mirroring-based back-to-origin configurations:

    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";
    
            // Create an OSSClient instance. 
            OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
    
            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();
                }
            }
        }
    }
  • Delete mirroring-based back-to-origin configurations

    The following sample code provides an example on how to delete the mirroring-based back-to-origin configurations:

    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";
    
            // Create an OSSClient instance. 
            OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
    
            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();
                }
            }
        }
    }

References

  • For the complete sample code that is used to configure static website hosting and mirroring-based back-to-origin, visit GitHub.

  • For more information about the API operation that you can call to configure static website hosting or mirroring-based back-to-origin, see PutBucketWebsite.

  • For more information about the API operation that you can call to query static website hosting configurations or mirroring-based back-to-origin rules, see GetBucketWebsite.

  • For more information about the API operation that you can call to delete static website hosting configurations or mirroring-based back-to-origin rules, see DeleteBucketWebsite.