All Products
Search
Document Center

Object Storage Service:Map a custom domain name to the default domain name of a bucket

Last Updated:Mar 20, 2025

For security reasons, accessing certain Object Storage Service (OSS) objects by using the default domain name of the bucket may trigger forced downloads or prohibit downloads. To preview or download these objects in a browser, you must map a custom domain name to the bucket and access the objects by using the custom domain name. Mapping a custom domain name does not affect the default domain name of the bucket, which can still be used to access OSS objects in the bucket.

Scenarios

  • Preview objects: For security purposes, when you access OSS objects by using the default domain name of a bucket, OSS automatically adds a download response header. This results in the browser forcing a download of the objects. However, when you use a custom domain name to access the same objects, OSS does not add the download response header. This enables the objects to be previewed directly in the browser instead of being downloaded. For information about the effective time and scope of automatic downloads triggered by accessing OSS objects by using default domain names, see Appendix: x-oss-ec rules triggered for forcible download.

  • Access .apk or .ipa objects: For security purposes, accessing .apk or .ipa objects by using the default domain name of a bucket results in a 400 error with the ApkDownloadForbidden error code. However, access to the same objects by using a custom domain name is not restricted. For information about the effective time and scope of blocked access triggered by accessing OSS objects by using default domain names, see Appendix.

  • Improve brand images and professionalism: Mapping custom domain names to OSS buckets enhances brand identities, reinforces professionalism, and builds user trust.

  • Bypass domain name blocking: Some applications or platforms may block the default domain names of buckets. To ensure access to the resources in your OSS bucket, we recommend that you map a custom domain name to your bucket.

  • Improve access convenience: A custom domain name is easier to remember than a default domain name. It simplifies access, enhances user-friendliness, and makes resource sharing more efficient.

  • Ensure URL persistence: After you map a custom domain name to an OSS bucket, the same domain name can continue to be used for accessing resources, even if the storage location or service changes. This ensures the persistence of the resource URL, allowing long-term access and use of the resources.

Limitations

  • Custom domain names containing Chinese characters are not supported.

  • Custom domain names that have already been mapped for image processing cannot be mapped to buckets again.

  • Each custom domain name can be mapped to only one bucket.

  • You can map up to 100 custom domain names to each bucket.

  • The OSS console does not support mapping a wildcard domain name to a bucket. For example, a domain name starting with an asterisk (*) cannot be mapped to a bucket. If such a domain name is mapped, all subdomains of that domain name will point to the bucket. However, when you use Alibaba Cloud CDN to accelerate access to a bucket, a wildcard domain name can be mapped to a bucket. In this case, the domain name will not be visible in the OSS console.

Prerequisites

  • An OSS bucket is created. For more information, see Create a bucket.

  • A custom domain name is registered. You can map a domain name registered with a third-party provider to a bucket in Alibaba Cloud. If you do not have a domain name, you can register one by using Alibaba Cloud Domains service platform. For more information, see Register a domain name on Alibaba Cloud.

  • An Internet Content Provider (ICP) filing is obtained for your domain name, and real-name verification is completed for your Alibaba Cloud account if the bucket to which the domain name is to be mapped is located in the Chinese mainland. For more information about IPC filings and real-name verification, see ICP filing process and FAQ about real-name verification of Alibaba Cloud accounts.

Procedure

Step 1: Map a custom domain name

The process for mapping a custom domain name to a bucket varies depending on the domain registrar and the owning account. You can query the domain registrar on the Alibaba Cloud WHOIS page and check the associated owning account in the Alibaba Cloud DNS console.

Map a domain name registered by using the current Alibaba Cloud account

To map a custom domain name that is registered by using the current Alibaba Cloud account, perform the following steps:

  1. Log on to the OSS console.

  2. In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.

  3. In the left-side navigation pane, choose Bucket Settings > Domain Names.

  4. On the Domain Names page, click Map Custom Domain Name.

  5. In the Map Custom Domain Name panel, enter the custom domain name, such as static.example.com, and click Confirm.

    Sample custom domain names

    Scenario

    Domain name

    Description

    Static website hosting

    example.com

    A root domain name. Users can access all website content hosted on OSS by using the root domain name.

    Static resource service

    static.example.com

    A subdomain name. The subdomain name can be used to centrally manage and serve static resources, such as images, style sheets, and scripts.

    Image service

    images.example.com

    A subdomain name. The subdomain name can be used to provide image resources for your website or mobile application.

    Video storage and playback

    video.example.com

    A subdomain name. The subdomain name can be used to store video resources.

    Object sharing and downloading

    downloads.example.com

    A subdomain name. The subdomain name can be used to provide efficient download services.

    Backup and log storage

    backup.example.com

    A subdomain name. The subdomain name can be used to store data backups or log files. It helps optimize the data management process.

    API document hosting

    docs.example.com

    A subdomain name. The subdomain name provides a centralized location for developers to access API documentation.

  6. Add a CNAME record to map the static.example.com domain name to the default domain name of your bucket.

    Automatically add a CNAME record

    In the Map Custom Domain Name panel, turn on Automatically Add CNAME Record.

    1.png

    After you turn on the toggle, the CNAME record is automatically added in Alibaba Cloud DNS, as shown in the following figure.1.png

    Manually add a CNAME record

    If you do not turn on Automatically Add CNAME Record in the Map Custom Domain Name panel, manually add a CNAME record in the Alibaba Cloud DNS console by using the following steps:

    1. Log on to the Alibaba Cloud DNS console.

    2. Choose Public DNS Resolution > Authoritative DNS Resolution. On the Authoritative Domain Names tab, find the domain name and click DNS Settings in the Actions column.

    3. On the DNS Settings tab, click Add DNS Record. In the Add DNS Record dialog box, configure the parameters described in the following table.

      Parameter

      Description

      Example

      Record Type

      The type of the DNS record that you want to add. Select CNAME to map a domain name to another domain name.

      CNAME

      Hostname

      The prefix of the domain.

      static

      DNS Request Source

      The DNS line that you want to use to resolve the domain name. We recommend that you select Default for this parameter to allow the DNS system to automatically select an optimal line.

      Default

      Record Value

      The public domain name of the bucket. The domain name of a bucket is in the <bucketname>.<endpoint> format. For more information about the public endpoints of different regions, see Regions and endpoints.

      examplebucket.oss-cn-hangzhou.aliyuncs.com

      TTL

      The update interval of the record. Keep the default value.

      Note

      The TTL period setting may experience a delay before it takes effect.

      10 Minutes

    4. Click OK.

      The CNAME record appears in the DNS record list of the domain name in Alibaba Cloud DNS, as shown in the following figure.1.png

Map a domain name registered by using a different Alibaba Cloud account

To map a domain name registered by using Alibaba Cloud A to an OSS bucket created by using Alibaba Cloud B, perform the following steps:

  1. Use Alibaba Cloud Account B to obtain the hostname and value of the TXT record.

    1. Log on to the OSS console.

    2. In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.

    3. In the left-side navigation pane, choose Bucket Settings > Domain Names.

    4. On the Domain Names page, click Map Custom Domain Name.

    5. In the Map Custom Domain Name panel, enter the domain name registered by using Alibaba Cloud A, such as static.example.com, and copy the values of the Hostname and Record Value parameters.

      Sample custom domain names

      Scenario

      Domain name

      Description

      Static website hosting

      example.com

      A root domain name. Users can access all website content hosted on OSS by using the root domain name.

      Static resource service

      static.example.com

      A subdomain name. The subdomain name can be used to centrally manage and serve static resources, such as images, style sheets, and scripts.

      Image service

      images.example.com

      A subdomain name. The subdomain name can be used to provide image resources for your website or mobile application.

      Video storage and playback

      video.example.com

      A subdomain name. The subdomain name can be used to store video resources.

      Object sharing and downloading

      downloads.example.com

      A subdomain name. The subdomain name can be used to provide efficient download services.

      Backup and log storage

      backup.example.com

      A subdomain name. The subdomain name can be used to store data backups or log files. It helps optimize the data management process.

      API document hosting

      docs.example.com

      A subdomain name. The subdomain name provides a centralized location for developers to access API documentation.

  2. Use Alibaba Cloud Account A to add a TXT record.

    1. Log on to the Alibaba Cloud DNS console.

    2. In the domain list, find the domain name that you want to map and click DNS Settings in the Actions column.

    3. On the DNS Settings tab, click Add DNS Record. In the Add DNS Record dialog box, configure the parameters described in the following table.

      Parameter

      Description

      Example

      Record Type

      The type of the DNS record that you want to add. Select TXT.

      TXT

      Hostname

      The root domain name is automatically filled in. You do not need to manually enter the root domain part.

      • To map the root domain name, enter _dnsauth. For example, if the root domain name is example.com, enter _dnsauth in the text box.

      • To map a subdomain, enter _dnsauth.<domain prefix>. For example, to map static.example.com to the bucket, enter _dnsauth.static in the text box.

      _dnsauth.static

      DNS Request Source

      The DNS line that you want to use to resolve the domain name. We recommend that you select Default for this parameter to allow the DNS system to automatically select an optimal line.

      Default

      Record Value

      The record value (CnameToken) of the TXT record that was recorded earlier by using Alibaba Cloud Account B.

      b0d777f7ccddeae93358d908ed59****

      TTL

      The update interval of the record. Keep the default value.

      Note

      The TTL period setting may experience a delay before it takes effect.

      10 Minutes

    4. Click OK.

  3. Log on to the OSS console with Alibaba Cloud Account B and go to the Map Custom Domain Name panel. Click Verify Domain Name Ownership.

  4. Use Alibaba Cloud Account A to add a CNAME record.

    1. In the domain list, find the domain name that you want to map and click DNS Settings in the Actions column.

    2. On the DNS Settings tab, click Add DNS Record. In the Add DNS Record dialog box, configure the parameters described in the following table.

      Parameter

      Description

      Example

      Record Type

      The type of the DNS record that you want to add. Select CNAME.

      CNAME

      Hostname

      The hostname.

      • If the domain name is a root domain name, such as example.com, enter @ in the text box.

      • If the domain name is a subdomain name, enter the prefix of the subdomain name in the text box. For example, if the subdomain name is static.example.com, enter static.

      static

      DNS Request Source

      The DNS line that you want to use to resolve the domain name. We recommend that you select Default for this parameter to allow the DNS system to automatically select an optimal line.

      Default

      Record Value

      The public domain name of the bucket. The domain name of a bucket is in the <bucketname>.<endpoint> format. For more information about the public endpoints of different regions, see Regions and endpoints.

      examplebucket.oss-cn-hangzhou.aliyuncs.com

      TTL

      The update interval of the record. Keep the default value.

      Note

      The TTL period setting may experience a delay before it takes effect.

      10 Minutes

    3. Click OK.

Map a domain name registered with a third-party provider

To map a domain name registered with a third-party provider to an OSS bucket, perform the following steps:

  1. In the OSS console, generate a hostname and value as a TXT record.

    1. Log on to the OSS console.

    2. In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.

    3. In the left-side navigation pane, choose Bucket Settings > Domain Names.

    4. On the Domain Names page, click Map Custom Domain Name.

    5. In the Map Custom Domain Name panel, enter the custom domain name registered with a third-party provider, such as static.example.com, and copy the values of the Hostname and Record Value parameters.

      Sample custom domain names

      Scenario

      Domain name

      Description

      Static website hosting

      example.com

      A root domain name. Users can access all website content hosted on OSS by using the root domain name.

      Static resource service

      static.example.com

      A subdomain name. The subdomain name can be used to centrally manage and serve static resources, such as images, style sheets, and scripts.

      Image service

      images.example.com

      A subdomain name. The subdomain name can be used to provide image resources for your website or mobile application.

      Video storage and playback

      video.example.com

      A subdomain name. The subdomain name can be used to store video resources.

      Object sharing and downloading

      downloads.example.com

      A subdomain name. The subdomain name can be used to provide efficient download services.

      Backup and log storage

      backup.example.com

      A subdomain name. The subdomain name can be used to store data backups or log files. It helps optimize the data management process.

      API document hosting

      docs.example.com

      A subdomain name. The subdomain name provides a centralized location for developers to access API documentation.

  2. On the DNS platform of your domain registrar, use the parameters described in the following table to add a TXT record.

    Parameter

    Description

    Example

    Record type

    The type of the DNS record that you want to add. Select TXT.

    TXT

    Hostname

    If the DNS platform automatically populates the root domain name, you do not need to manually enter the root domain part.

    • To map the root domain name, enter _dnsauth. For example, if the root domain name is example.com, enter _dnsauth in the text box.

    • To map a subdomain, enter _dnsauth.<domain prefix>. For example, to map static.example.com to the bucket, enter _dnsauth.static in the text box.

    _dnsauth.static

    Record value

    The record value (CnameToken) of the TXT record that was recorded earlier from OSS.

    b0d777f7ccddeae93358d908ed59****

  3. Return to the Map Custom Domain Name panel in the OSS console. Click Verify Domain Name Ownership.

  4. On the DNS platform of your domain registrar, use the parameters described in the following table to add a CNAME record.

    Parameter

    Description

    Example

    Record type

    The type of the DNS record that you want to add. Select CNAME.

    CNAME

    Hostname

    The hostname.

    • If the domain name is a root domain name, such as example.com, enter @ in the text box.

    • If the domain name is a subdomain name, enter the prefix of the subdomain name in the text box. For example, if the subdomain name is static.example.com, enter static.

    static

    Record value

    The public domain name of the bucket. The domain name of a bucket is in the <bucketname>.<endpoint> format. For more information about the public endpoints of different regions, see Regions and endpoints.

    examplebucket.oss-cn-hangzhou.aliyuncs.com

Step 2: Verify the custom domain name

After you map a custom domain name to the bucket, any request made by using the custom domain name will be resolved to the default domain name of the bucket through DNS. To verify the DNS records of the custom domain name, you can run the nslookup or dig command.

nslookup

Replace static.example.com in the following command with your actual domain name and run the command:

nslookup -type=CNAME static.example.com

If the command output displays the public domain name of your bucket, the DNS records have taken effect.

1.png

dig

Replace static.example.com in the following command with your actual domain name and run the command:

dig CNAME static.example.com

If the command output displays the public domain name of your bucket, the DNS records have taken effect.

2.png

Step 3: Use the custom domain name

After the DNS records of a custom domain name take effect, you can construct a URL by using the HTTP protocol and the custom domain name, which includes the signature and validity period. The URL format is http://YourDomain/ObjectName?SignatureInformation. You can then use the URL to access the object in the OSS bucket.

  1. Obtain a presigned URL.

    Use the OSS console

    1. Log on to the OSS console.

    2. In the left-side navigation pane, click Buckets. On the Buckets page, click the name of the bucket.

    3. In the left-side navigation tree, choose Object Management > Objects.

    4. On the Objects page, click the name of the object.

    5. In the View Details panel, select the custom domain name that is mapped to the bucket in the Custom Domain Name field, retain the default settings for other parameters, and then click Copy Object URL.

      2.png

    Use ossbrowser

    You can use ossbrowser to perform the same object-level operations that you can perform in the OSS console. You can follow the on-screen instructions in ossbrowser to obtain a presigned URL. For information about how to download ossbrowser, see ossbrowser 1.0.

    1. Use the custom domain name to log on to ossbrowser.

    1. Obtain the URL of the object.

    Use OSS SDKs

    You can use the custom domain name to create an OssClient instance and generate a presigned URL.

    Java

    import com.aliyun.oss.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.comm.SignVersion;
    
    import java.net.URL;
    import java.util.Date;
    
    public class Demo {
        public static void main(String[] args) throws Throwable {
            // Specify the custom domain name. Example: static.example.com.
            String endpoint = "http://static.example.com";
            // Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou.
            String region = "cn-hangzhou";
    
            // Obtain access credentials from environment variables. Before you run the sample code, make sure that the environment variables are configured.
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
    
            // Create an OSSClient instance.
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            // Set this parameter to true to enable CNAME.
            clientBuilderConfiguration.setSupportCname(true);
            // Explicitly declare the use of the V4 signature algorithm
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
            OSS ossClient = OSSClientBuilder.create()
                    .endpoint(endpoint)
                    .credentialsProvider(credentialsProvider)
                    .clientConfiguration(clientBuilderConfiguration)
                    .region(region)
                    .build();
    
            try {
                // Specify the validity period of the presigned URL. Unit: milliseconds. In this example, the validity period is set to 1 hour.
                Date expiration = new Date(new Date().getTime() + 3600 * 1000L);
                // Generate a presigned URL that allows HTTP GET requests.In this example, no additional request headers are specified. Other users can access relevant content directly by using the browser.
                String bucketName = "examplebucket";
                String objectName = "demo.png";
                URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
                System.out.println(url);
            } 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();
                }
            }
        }
    }

    Python

    # -*- coding: utf-8 -*-
    import oss2
    from oss2.credentials import EnvironmentVariableCredentialsProvider
    
    # Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    
    # Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
    region = "cn-hangzhou"
    
    # Specify the custom domain name. Example: static.example.com.
    endpoint = 'http://static.example.com'
    
    # Specify the name of your bucket.
    bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region, is_cname=True)
    
    
    # Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt.
    object_name = 'exampledir/exampleobject.txt'
    
    # Generate a signed URL that is used to download the object. In this example, the validity period of the URL is 600 seconds.
    # By default, OSS identifies forward slashes (/) in the full path of an object as escape characters in the signing process. Therefore, the signed URL cannot be directly used.
    # Set the slash_safe parameter to True. This way, OSS does not identify the forward slashes (/) in the full path of the object as escape characters, and the signed URL can be directly used.
    url = bucket.sign_url('GET', object_name, 600, slash_safe=True, params=params)
    print('The signed URL is:', url)

    Node.js

    const OSS = require("ali-oss");
    
    // Specify a function used to generate a signed URL.
    async function generateSignatureUrl(fileName) {
      // Obtain the signed URL.
      const client = await new OSS({
          // Specify the custom domain name that you want to map to the bucket.
          endpoint: 'http://static.example.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.
          accessKeyId: process.env.OSS_ACCESS_KEY_ID,
          accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
          bucket: 'examplebucket',
          // Specify the region in which the bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
          region: 'oss-cn-hangzhou',
          authorizationV4: true,
          cname: true
      });
    
      return await client.signatureUrlV4('GET', 3600, {
          headers: {} // Specify the request headers based on the actual request headers.
      }, fileName);
    }
    // Call the function and pass in the name of the object.
    generateSignatureUrl('yourFileName').then(url => {
      console.log('Generated Signature URL:', url);
    }).catch(err => {
      console.error('Error generating signature URL:', err);
    });

    PHP

    <?php
    if (is_file(__DIR__ . '/../autoload.php')) {
        require_once __DIR__ . '/../autoload.php';
    }
    if (is_file(__DIR__ . '/../vendor/autoload.php')) {
        require_once __DIR__ . '/../vendor/autoload.php';
    }
    
    use OSS\OssClient;
    use OSS\Core\OssException;
    use OSS\Http\RequestCore;
    use OSS\Http\ResponseCore;
    use OSS\Credentials\EnvironmentVariableCredentialsProvider;
    
    // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
    $provider = new EnvironmentVariableCredentialsProvider();
    // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to http://static.example.com.
    $endpoint = "http://static.example.com";
    // Specify the name of the bucket.
    $bucket= "examplebucket";
    // Specify the full path of the object. Do not include the bucket name in the full path.
    $object = "exampleobject.txt";
    // Set the validity period of the signed URL to 600 seconds. Maximum value: 32400.
    $timeout = 600;
    try {
        $config = array(  
            "provider" => $provider,
            "endpoint" => $endpoint,
            'signatureVersion'=>OssClient::OSS_SIGNATURE_VERSION_V4,
            "cname"	=> true,
            "region"=> "cn-hangzhou"
        );
        $ossClient = new OssClient($config);
        // Generate a signed URL.
        $signedUrl = $ossClient->signUrl($bucket, $object, $timeout, "GET");
        print_r($signedUrl);
    } catch (OssException $e) {
        printf(__FUNCTION__ . ": FAILED\n");
        printf($e->getMessage() . "\n");
        return;
    }

    Go

    package main
    
    import (
    	"context"
    	"flag"
    	"log"
    	"time"
    
    	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
    	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
    )
    
    // Specify the global variables.
    var (
    	region     string // Region in which the bucket is located.
    	bucketName string // Name of the bucket.
    	objectName string // Name of the object.
    )
    
    // Specify the init function used to initialize command line parameters.
    func init() {
    	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
    	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
    	flag.StringVar(&objectName, "object", "", "The name of the object.")
    }
    
    func main() {
    	// Parse command line parameters.
    	flag.Parse()
    
    	// Check whether the name of the bucket is specified.
    	if len(bucketName) == 0 {
    		flag.PrintDefaults()
    		log.Fatalf("invalid parameters, bucket name required")
    	}
    
    	// Check whether the region is specified.
    	if len(region) == 0 {
    		flag.PrintDefaults()
    		log.Fatalf("invalid parameters, region required")
    	}
    
    	// Check whether the object is specified.
    	if len(objectName) == 0 {
    		flag.PrintDefaults()
    		log.Fatalf("invalid parameters, object name required")
    	}
    
    	// Load the default configurations and specify the credential provider and region.
    	cfg := oss.LoadDefaultConfig().
    		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
    		WithRegion(region).
    		WithEndpoint("http://static.example.com").
    		WithUseCName(true)
    
    	// Create an OSS client.
    	client := oss.NewClient(cfg)
    
    	// Generate a signed URL for the GetObject request.
    	result, err := client.Presign(context.TODO(), &oss.GetObjectRequest{
    		Bucket: oss.Ptr(bucketName),
    		Key:    oss.Ptr(objectName),
    		//RequestPayer: oss.Ptr("requester"), // 指定请求者身份
    	},
    		oss.PresignExpires(10*time.Minute),
    	)
    	if err != nil {
    		log.Fatalf("failed to get object presign %v", err)
    	}
    
    	log.Printf("request method:%v\n", result.Method)
    	log.Printf("request expiration:%v\n", result.Expiration)
    	log.Printf("request url:%v\n", result.URL)
    	if len(result.SignedHeaders) > 0 {
    		// If you specify request headers when you generate a signed URL that allows HTTP GET requests, make sure that the request headers are included in the GET request initiated by using the signed URL. This prevents request failures and signature errors.
    		log.Printf("signed headers:\n")
    		for k, v := range result.SignedHeaders {
    			log.Printf("%v: %v\n", k, v)
    		}
    	}
    }

    Use ossutil

    Use the custom domain name to generate a presigned URL for an object by running the presign command.

    ossutil presign oss://examplebucket/exampleobject.txt --endpoint "http://static.example.com” --addressing-style "cname"

    To enable the ossutil command to automatically use a custom domain name, instead of manually specifying it each time, add the custom domain name to the configuration file.

  2. Access the presigned URL in a browser.

    2023-11-07_11-01-40.png

API operations

  • For more information about the API operation that you can call to create a CNAME token for domain ownership verification, see CreateCnameToken.

  • For more information about the API operation that you can call to query CNAME tokens, see GetCnameToken.

  • For more information about the API operation that you can call to map a custom domain name to a bucket, see PutCname.

  • For more information about the API operation that you can call to query all CNAME records that point to the domain names of a bucket, see ListCname.

  • For more information about the API operation that you can call to delete a CNAME record of a bucket, see DeleteCname.

  • For more information about the API operation that you can call to add a TXT record or a CNAME record, see AddDomainRecord.

What to do next

Access an OSS object over HTTPS

By default, access over HTTPS is not supported for a custom domain name if no SSL certificate is configured. When you attempt to access an object by using a custom domain name over HTTPS, the browser will display an insecure connection warning. To enable HTTPS access, an SSL certificate must be configured for the custom domain name.

httpsandpresigned

Access an OSS object by using a non-signed and permanently valid URL

Warning

If the URL that you obtain is in the tttp://YourDomainName/ObjectName format, it does not include a signature or expiration time. To use this URL to access an object, make sure the access control list (ACL) of the object is public-read. However, a public-read ACL allows any Internet user to access the object, which potentially leads to data leaks and increased costs. For enhanced security, we recommend that you use a URL that includes a signature and expiration time.

You can use one of the following methods to grant public-read access to an object:

  • Set the ACL of an object to public-read: You can set the ACL of an OSS object to public-read. This makes the URL of the object permanently accessible to anyone. To block access from unauthorized websites, enable hotlink protection in OSS.

  • Use Alibaba Cloud CDN to accelerate access: To ensure secure access control for an OSS object, you can set its ACL to private and makes it publicly accessible by using Alibaba Cloud CDN. This makes the URL of the object permanently accessible to anyone. To block access from unauthorized websites, enable hotlink protection in Alibaba Cloud CDN.

https

Prevent unauthorized use of OSS objects by other websites

By default, OSS objects can be accessed and displayed by any website. This can lead to unnecessary request and outbound traffic fees. To mitigate this risk, enable hotlink protection by configuring a Referer blacklist or whitelist. This restricts access to intended users. After hotlink protection is enabled, unauthorized websites will be blocked from linking to your objects, and failed requests will not incur request fees and outbound traffic fees.

Host static websites on OSS

To use OSS as a static website server for storing and delivering static resources, such as HTML, CSS, and JavaScript resources over the Internet, you must map a custom domain name to the OSS bucket and configure static website hosting.

Enhance OSS object download speeds across regions

For example, if your OSS objects are stored in China (Hangzhou), Alibaba Cloud CDN can accelerate access to these objects for users in other regions. When Alibaba Cloud CDN is enabled, OSS objects are cached at regional points of presence (POPs). Users accessing these objects are automatically routed to the nearest POP, ensuring faster and more efficient downloads.

Note

We recommend that you use the CDN-accelerated domain name for downloads to benefit from accelerated access and the default domain name of the bucket for uploads to optimize performance across regions.

Optimize long-distance transmission of OSS objects

For example, if your OSS objects are stored in China (Hangzhou), users accessing them from outside the Chinese mainland may encounter slow uploads and downloads. To enhance cross-border access speed and stability, you can enable Transfer acceleration. This feature maps a custom domain name to the OSS-accelerated domain name of your bucket.

FAQ

Why am I unable to preview object content after configuring Content-Disposition: Inline?

When a request is made to access a website file or image in a bucket from a browser by using the default bucket domain name (<bucketName>.oss-<regionId>.aliyuncs.com) or OSS-accelerated domain name (<bucketName>.oss-accelerate.aliyuncs.com), OSS includes the x-oss-force-download: true and Content-Disposition: attachment headers in the response to ensure security. The Content-Disposition: attachment header triggers a forced download in the browser, even if the request contains the Content-Disposition: inline header.

To enable object content preview in the browser, map a custom subdomain of your registered domain name to the bucket and use the custom subdomain to access objects in the bucket from a browser. In this case, OSS does not include the headers that specify a forced download in the response. As a result, the browser decides how to handle the content based on the Multipurpose Internet Mail Extensions (MIME) type of the content. The browser displays most MIME types inline instead of downloading them.

How can I complete ICP filing for a static website hosted on an OSS bucket?

If you are using Alibaba Cloud OSS to host a static website, take note that OSS does not support ICP filing. To comply with ICP filing requirements, follow these steps:

  1. Purchase an Elastic Compute Service (ECS) instance with the minimum configuration and ensure that the subscription duration is at least three months to meet ICP filing requirements.

  2. Use the purchased ECS instance to complete the ICP filing process.

  3. Once the ICP filing is approved, point the filed domain name to your OSS bucket.

What should I do if I receive an error indicating that a CNAME record cannot be added automatically because the hostname already exists?

Causes

If an existing hostname matches that of the CNAME record to be added automatically, it may result from one of the following causes:

  • Hostname conflict. The hostname is used by a different type of DNS record, such as an A record.

  • Duplicate records: The hostname is used by another CNAME record. For example, you have already manually added an identical CNAME record.

Solutions

To resolve this issue, follow these steps in the Alibaba Cloud DNS console based on your requirements:

  • If you want to keep the existing DNS record that uses the hostname, use a different subdomain for domain mapping.

  • If you do not want to keep the existing DNS record, perform one of the following operations as needed:

    • If the existing record is not a CNAME record, delete the existing record, add a new CNAME record with the same hostname, and then resolve it to the default bucket domain name.

    • If the existing record is a CNAME record, modify the record to point to the default bucket domain name.

What do I do if the custom domain name I want to use is already mapped to another bucket?

If the custom domain name you want to use is already mapped to another bucket, resolve the issue by using one of the following methods:

  • Use a subdomain of the desired domain name. For example, if oss.example.com is already mapped to another bucket, create a subdomain like static.example.com and map it to your bucket.

  • Unmap and re-map the domain name. For example, if oss.example.com is mapped to another bucket, unmap it from that bucket and then map it to your bucket.

    What do I do if I want to unmap a domain name from an OSS bucket?

    1. If Alibaba Cloud CDN is enabled, you must disable it before you can unmap a domain name from the OSS bucket.

      To disable Alibaba Cloud CDN, you must modify the origin server settings to remove the association between the accelerated domain name and the OSS bucket. For information about how to modify the origin server settings, see Configure an origin server.

    2. Unmap the domain name from the OSS bucket.

      1. Log on to the OSS console.

      2. In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.

      3. In the left-side navigation tree, choose Bucket Settings > Domain Names.

      4. On the Domain Names page, find the custom domain name that you want to unmap and click Manage Mapping Configurations in the Actions column.

      5. In the Manage Mapping Configurations panel, click Unmap. In the message that appears, click OK.

    3. Delete the DNS records of the domain name.

      After you unmap the domain name, delete its TXT record and CNAME record. For more information, see Delete a DNS record.

How do I fix a NeedVerifyDomainOwnership error code?

Why am I unable to preview object content after mapping a custom domain name to my bucket?

If you have mapped a custom domain name to your bucket and the CNAME record is in effect, but you cannot preview object content in a browser, follow these steps to troubleshoot the issue:

Setting

Cause

Solution

OSS

The Content-Type header value does not match the actual object type. In this case, the browser cannot parse or render the object correctly and can only download the object.

To resolve this issue, update the Content-Type header value to reflect the correct object type. For more information, see How do I configure the Content-Type header?

The Content-Disposition header is set to attachment, which prompts the browser to download the object rather than display its content.

To ensure the content is displayed directly in the browser, set the Content-Disposition header to inline. For more information, see Manage object metadata.

CDN

Resources cached on POPs are not refreshed.

Refresh the resources cached on POPs. For more information, see Purge and prefetch resources.

Browser

Previewing objects in .doc, .ppt, .pdf, and .mov formats is not supported.

  • Install a plug-in for the browser to support previewing objects in these formats.

  • For objects in the .doc, .ppt and .pdf formats, you can use WebOffice to preview their content online without the need for browser plug-ins.

  • For objects in the .mov format, you can preview the content after transcoding.

Can I still access an object by using its original URL after I map a custom domain name to the bucket?

Yes, you can. For more information about how to generate object URLs, see Download an object by using a presigned URL.

Is accessing objects based on a custom domain name performed over the Internet?

Access by using a custom domain name typically occurs over the Internet. Since Internet users often need to preview OSS objects, a custom domain name of a bucket is, by default, resolved to its public domain name. This ensures accessibility for Internet users.

How can I ensure an object is downloaded when it is accessed by using a custom domain name in a browser?

To ensure an object is downloaded when it is accessed by using a custom domain name in a browser, set the Content-Disposition header to attachment. For more information, see How do I force a download of an object from an OSS bucket when the object is accessed by using a custom domain of the bucket?

What do I do if the configured DNS record does not take effect?

If the configured DNS record is not working, the issue may be due to local DNS cache. To resolve this, clear the DNS cache by using the following command and retry again:

Window

 ipconfig /flushdns

macOS

 sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder

Linux

 sudo systemd-resolve --flush-caches

Why do some browsers play videos within <video> tags instead of downloading them, even when the server sets the Content-Disposition header to attachment?

When videos are within <video> tags, the browser requests the video stream and prioritizes the MIME type. If the server returns a playable MIME type, such as video/mp4, the browser will play the video and disregard the Content-Disposition: attachment header.