Object Storage Service (OSS) generates a URL for an object uploaded to a bucket by using the default domain name of the bucket. When you access the object by using its URL from a browser, the object is downloaded. If your business application requires you to hide the default domain name of your bucket or enable object previews upon object access from browsers, you need to map a custom domain name to your bucket and use the custom domain to access objects. Mapping a custom domain name to a bucket does not affect your use of the OSS domain names of the bucket.
Prerequisites
A bucket is created. For more information, see Create a bucket.
A second-level domain name is registered. You can map a domain name that is not registered with Alibaba Cloud to a bucket. If you do not have a domain name, you can register one with Alibaba Cloud Domain Names. For more information, see Register a domain name on Alibaba Cloud.
An Internet Content Provider (ICP) filing is obtained for your domain name if the bucket to which you want to map the domain name resides in the Chinese mainland. You can map a domain name whose ICP filing is not completed by using the Alibaba Cloud ICP Filing system. If you have not applied for an ICP filing for your domain name, you can apply for an ICP filing by using the Alibaba Cloud ICP Filing system. For more information, see ICP filing application overview.
Scenarios
Object preview: If you use a custom domain name of a bucket to access an object in the bucket from a browser, OSS does not add a response header that forces a download of the object. This way, the object is displayed for content preview directly in the browser.
Brand identity: A custom domain name helps maintain a consistent brand identity and build customer trust.
Bypassing domain blocking: Some applications or platforms may block default bucket domain names. You can map a custom domain name to a bucket to maintain access to the bucket.
Ease of use: A custom bucket domain name is generally easier to remember than a default domain name and provides a more user-friendly experience of resource accessing and sharing.
User experience optimization: A custom domain name is a user-friendly address that helps users initiate a resource request faster. You can also use a custom domain name together with Alibaba Cloud CDN to accelerate content delivery and download. This deceases latency and improves user experience.
URL availability: A custom domain name of a bucket maintains persistent access to objects in the bucket by using the same domain name even if the storage path or service is changed.
Mechanisms
This section describes how OSS behaves when you use a default bucket name and a custom bucket name to access an object from a browser.
Access using a default domain name
For secure data transfers, OSS includes the x-oss-force-download: true
and Content-Disposition: attachment
headers in the response to a browser-based object request that uses a default bucket domain name, which is in the <bucketName>.oss-<regionId>.aliyuncs.com
format. The browser downloads the requested object if the Content-Disposition: attachment
header is present in the response. The following figure shows the process:
For more information about types of objects that OSS forcibly downloads and the effective time of forcible downloads, see Appendix: x-oss-ec rules triggered for forcible download.
Access using a custom domain name
If you map a custom subdomain of your registered domain name and map the subdomain to a bucket, you can 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 forcible download in the response. The browser detects no Content-Disposition
from the response and uses the default Content-Disposition: inline
header, which indicates that the content is displayed in the browser instead of being downloaded. The following figure shows the process:
Overview
Domain name mapping does not support domain names that contain Chinese characters.
Each domain name can be mapped to only one bucket.
Each bucket can be mapped to up to 100 domain names.
The OSS console does not support mapping between a generic domain name and a bucket. For example, you cannot map a domain name whose prefix is * and whose subdomains point to a default bucket domain name. If you use Alibaba Cloud CDN to accelerate access to a bucket, you can map a generic domain name to the bucket. However, the domain name is not displayed in the OSS console.
Procedure
Step 1: Map a custom domain name
The steps of mapping a custom domain name to a bucket vary based on the owner account and domain registrar.
You can query the registrar of a domain name at .
You can query whether a domain name belongs to the current Alibaba Cloud account in the Alibaba Cloud DNS console.
Map a custom domain name registered using the current Alibaba Cloud account
To map a custom domain name that is registered using the current Alibaba Cloud account, perform the following steps:
Log on to the OSS console.
In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.
In the left-side navigation pane, choose Bucket Settings > Domain Names.
On the Domain Management page, click Map Custom Domain Name.
In the Map Custom Domain Name panel, enter the domain name that you want to map to the bucket in the Domain Name field, turn on Automatically Add CNAME Record, and click Submit.
Alibaba Cloud DNS automatically adds a CNAME record that points the custom domain name to the public domain name of the bucket.
NoteIf you do not turn on Automatically Add CNAME Record, you need to manually add a CNAME record for the custom domain name in the Alibaba Cloud DNS console so that the mapping can take effect.
Map a custom domain name registered using another Alibaba Cloud account
To map a custom domain name that is registered using Alibaba Cloud Account A to a bucket in Alibaba Cloud Account B, perform the following steps:
Use Alibaba Cloud Account B to obtain the hostname and value in the TXT record of the domain name.
Log on to the OSS console.
In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.
In the left-side navigation pane, choose Bucket Settings > Domain Names.
On the Domain Management page, click Map Custom Domain Name.
In the Map Custom Domain Name panel, enter the domain name that you want to map to the bucket in the Domain Name field and click Obtain TXT. Record the Hostname and Value.
ImportantAfter you record the TXT record, do not close the Map Custom Domain Name panel until you submit the domain name. If you close the Map Custom Domain Name panel, the TXT record becomes invalid and the subsequent domain ownership verification fails.
Use Alibaba Cloud Account A to add a TXT record.
Log on to the Alibaba Cloud DNS console.
On the Domain Name Resolution page, find the domain name that you want to map and click DNS Settings in the Actions column.
On the DNS Settings page, click Add DNS Record. In the Add DNS Record panel, configure the parameters described in the following table.
Parameter
Description
Example
Record Type
Select TXT.
TXT
Hostname
Enter the hostname of the TXT record that was recorded earlier.
****59e5-4bbd-aef4-8e401dc13a0a.static
DNS Request Source
The DNS line that is used 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
Enter the record value of the TXT record that was recorded earlier.
oss-domain-verfication=17ca4f6a1247f459fb310****
TTL
Select the interval at which the record is updated. Keep the default value.
NoteThere is a certain delay before the TTL setting takes effect.
10 Minutes
Click OK.
Return to the Map Custom Domain Name panel in the OSS console, click I have added the TXT record. Continue submission..
Use Alibaba Cloud Account A to add a CNAME record.
On the Domain Name Resolution page, find the domain name that you want to map and click DNS Settings in the Actions column.
On the DNS Settings page, click Add DNS Record. In the Add DNS Record panel, configure the parameters described in the following table.
Parameter
Description
Example
Record Type
Select CNAME.
CNAME
Hostname
Enter a prefix of the domain name.
For a root domain, such as
example.com
, enter @.For a subdomain, enter the prefix of the subdomain. For example, if the domain name is
static.example.com
, enter static.
static
DNS Request Source
The DNS line that is used 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
Enter the public domain name of the bucket. The endpoint of a bucket follows the <bucketname>.<endpoint> format. For more information about public endpoints for different regions, see Regions and endpoints.
examplebucket.oss-cn-hangzhou.aliyuncs.com
TTL
Select the interval at which the record is updated. Keep the default value.
NoteThere is a certain delay before the TTL setting takes effect.
10 Minutes
Click OK.
Map a custom domain name that is not registered using an Alibaba Cloud account
To map a custom domain name that is registered with another domain provider, perform the following steps:
In the OSS console, generate a hostname and value as a TXT record for domain ownership verification.
Log on to the OSS console.
In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.
In the left-side navigation pane, choose Bucket Settings > Domain Names.
On the Domain Management page, click Map Custom Domain Name.
In the Map Custom Domain Name panel, enter the custom domain name that you want to map, click Obtain TXT, and record the Hostname and Value.
ImportantAfter you record the TXT record, do not close the Map Custom Domain Name panel until you submit the domain name. If you close the Map Custom Domain Name panel before you submit the custom domain name mapping, the TXT record becomes invalid and the subsequent domain ownership verification fails.
In the DNS platform of your domain provider, use the settings described in the following table to add a TXT record.
Parameter
Description
Example
Record type
Select TXT.
TXT
Hostname
Enter the hostname that was recorded earlier.
****59e5-4bbd-aef4-8e401dc13a0a.static
Record value
Enter the value of the TXT record that was recorded earlier.
oss-domain-verfication=17ca4f6a1247f459fb310****
Return to the Map Custom Domain Name panel in the OSS console, click I have added the TXT record. Continue submission..
In the DNS platform of your domain provider, use the settings described in the following table to add a CNAME record.
Parameter
Description
Example
Record type
Select CNAME.
CNAME
Hostname
Enter a prefix of the domain name.
For a root domain, such as
example.com
, enter @.For a subdomain, enter the prefix of the subdomain. For example, if the domain name is
static.example.com
, enter static.
static
Record value
Enter the public domain name of the bucket. The endpoint of a bucket follows the <bucketname>.<endpoint> format. For more information about public endpoints for different regions, see Regions and endpoints.
examplebucket.oss-cn-hangzhou.aliyuncs.com
Step 2: Verify the domain name mapping
After you map the custom domain name to the bucket, use the nslookup
or dig
command to check CNAME resolution. If the output shows that the CNAME is the public domain name of the bucket, the CNAME record takes effect.
nslookup
Replace example.com in the following command with the custom domain name that you mapped to the bucket and run the command:
nslookup -type=CNAME example.com
If the domain mapping is successful, the output is similar to the following content.
dig
Replace example.com in the following command with the custom domain name that you mapped to the bucket and run the command:
dig CNAME example.com
If the domain mapping is successful, the output is similar to the following content.
Step 3: Use the custom domain name to access the bucket
After the domain mapping takes effects, you can use the custom domain name to access the bucket over HTTP.
Upload an object to the bucket.
For more information, see Simple upload.
Generate object URLs.
Generate a temporary object URL
To obtain a temporary URL of an object, perform the following steps:
Set the access control list (ACL) of the object to private.
For more information, see Object ACLs.
Use the following methods to obtain the object URL that has a validity period. The URL of a private object is in the
http://YourDomain/ObjectName?Signature
format.
Use the OSS console
Log on to the OSS console.
In the left-side navigation pane, click Buckets. On the Buckets page, click the name of the bucket in which the private object is stored.
In the left-side navigation tree, choose
.On the Objects page, click the name of the object.
In the View Details panel, select the custom domain name that you mapped to the bucket in the Custom Domain Name field, retain the default settings for the other parameters, and click Copy Object URL.
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 signed URL. For more information about how to use ossbrowser, see Use ossbrowser.
Use OSS SDKs
Use the custom domain name to create an OSSClient instance.
Use the OSSClient instance to call the GeneratePresignedUrl operation to obtain a signed URL of the object.
For more information, see Add signatures to URLs.
Java
// Replace yourEndpoint with the custom domain name that you want to use. String endpoint = "yourEndpoint"; // Obtain the access credentials from the environment variables. You need to configure environment variables before you run the sample code. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Create a ClientBuilderConfiguration instance and modify the default parameters based on your business requirements. ClientBuilderConfiguration conf = new ClientBuilderConfiguration(); // Specify whether to use CNAME. CNAME is used to map the custom domain name to the bucket. conf.setSupportCname(true); // Create an OSSClient instance. OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider, conf); // Shut down the OSSClient instance. ossClient.shutdown();
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; // 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 = getenv("OSS_ACCESS_KEY_ID"); $accessKeySecret = getenv("OSS_ACCESS_KEY_SECRET"); // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. $endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; try { // true indicates that CNAME is enabled. If CNAME is enabled, a custom domain name is mapped to a bucket. $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, true); } catch (OssException $e) { print $e->getMessage(); }
Node.js
const OSS = require('ali-oss') const client = new OSS({ // Use a custom domain name as the endpoint of a bucket to access the bucket. endpoint: 'http://img.example.com', // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. accessKeyId: 'yourAccessKeyId', accessKeySecret: 'yourAccessKeySecret', cname: true });
Python
# -*- coding: utf-8 -*- import oss2 from oss2.credentials import EnvironmentVariableCredentialsProvider # Obtain access credentials from environment variables. You need to configure environment variables before you run the sample code. auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider()) # Specify the custom domain name that is mapped to the bucket. Example: example.com. cname = 'http://example.com' # Specify the name of the bucket, and set is_cname to True to enable CNAME. CNAME is used to map a custom domain name to a bucket. bucket = oss2.Bucket(auth, cname, 'examplebucket', is_cname=True)
Browser.js
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <script src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"></script> </head> <body> <script> const client = new OSS({ // Enter a custom domain name. Example: example.com. endpoint: "example.com", // Specify the temporary AccessKey pair obtained from Security Token Service (STS). The AccessKey pair consists of an AccessKey ID and an AccessKey secret. accessKeyId: "yourAccessKeyId", accessKeySecret: "yourAccessKeySecret", // Specify the security token obtained from STS. stsToken: 'yourSecurityToken', // Specify the name of the bucket. Example: examplebucket. bucket: "examplebucket", cname: true, }); </script> </body> </html>
.NET
using Aliyun.OSS; using Aliyun.OSS.Common; // 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. var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID"); var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET"); // Specify the custom domain name. const string endpoint = "yourDomain"; // Create a ClientConfiguration instance. Modify parameters as required. var conf = new ClientConfiguration(); // Specify that a CNAME record can be used. A CNAME record specifies the mapping relationship between a custom domain name and a bucket. conf.IsCname = true; // Create an OSSClient instance. var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
Android
// Specify a custom domain name. String endpoint = "yourEndpoint"; // Specify the temporary AccessKey pair obtained from STS. String accessKeyId = "yourAccessKeyId"; String accessKeySecret = "yourAccessKeySecret"; // Specify the security token obtained from STS. String securityToken = "yourSecurityToken"; OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken); // Create an OSSClient instance. OSSClient oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
Go
package main import ( "fmt" "github.com/aliyun/aliyun-oss-go-sdk/oss" "os" ) func main(){ // Obtain access credentials from environment variables. You need to configure environment variables before you run the sample code. provider, err := oss.NewEnvironmentVariableCredentialsProvider() if err != nil { fmt.Println("Error:", err) os.Exit(-1) } // Set yourEndpoint to the custom domain name of the bucket. // oss.UseCname(true) indicates that CNAME is enabled. CNAME is used to map a custom domain name to a bucket. client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider),oss.UseCname(true)) if err != nil { fmt.Println("Error:", err) os.Exit(-1) } fmt.Printf("client:%#v\n", client) }
iOS
// Specify a custom domain name. NSString *endpoint = @"yourEndpoint"; // Specify the temporary AccessKey pair obtained from STS. An AccessKey pair consists of an AccessKey ID and an AccessKey secret. NSString *accessKeyId = @"yourAccessKeyId"; NSString *accessKeySecret = @"yourAccessKeySecret"; // Specify the security token obtained from STS. NSString *securityToken = @"yourSecurityToken"; id<OSSCredentialProvider> credentialProvider = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:accessKeyId secretKeyId:accessKeySecret securityToken:securityToken]; OSSClient *client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credentialProvider];
C++
#include <alibabacloud/oss/OssClient.h> using namespace AlibabaCloud::OSS; int main(void) { /* Initialize information about the account that is used to access OSS. */ /* 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 https://oss-cn-hangzhou.aliyuncs.com. */ std::string Endpoint = "yourEndpoint"; /* Initialize resources such as network resources. */ InitializeSdk(); ClientConfiguration conf; /* 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. */ auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>(); OssClient client(Endpoint, credentialsProvider, conf); /* Release resources such as network resources. */ ShutdownSdk(); return 0; }
C
#include "oss_api.h" #include "aos_http_io.h" # Specify the custom domain name. */ const char *endpoint = "yourCustomEndpoint"; void init_options(oss_request_options_t *options) { options->config = oss_config_create(options->pool); /* Use a char* string to initialize data of the aos_string_t type. */ aos_str_set(&options->config->endpoint, endpoint); /* 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. */ aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID")); aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET")); /* Enable CNAME and map the custom domain name to your bucket. */ options->config->is_cname = 1; options->ctl = aos_http_controller_create(options->pool, 0); } int main() { aos_pool_t *p; oss_request_options_t *options; /* Initialize global variables. You need to initialize global variables only once in the program lifecycle. */ if (aos_http_io_initialize(NULL, 0) != AOSE_OK) { return -1; } /* Initialize the memory pool and options. */ aos_pool_create(&p, NULL); options = oss_request_options_create(p); init_options(options); /* The logic code. In this example, the logic code is omitted. */ /* Release the memory pool. This operation releases the memory resources allocated for the request. */ aos_pool_destroy(p); /* Release global resources that are allocated. You need to release global resources only once in the program lifecycle. */ aos_http_io_deinitialize(); return 0; }
Ruby
require 'aliyun/oss' client = Aliyun::OSS::Client.new( # Specify the custom domain name that you want to map to the bucket. endpoint: 'http://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. access_key_id: ENV['OSS_ACCESS_KEY_ID'], access_key_secret: ENV['OSS_ACCESS_KEY_SECRET'] cname: true) )
Use ossutil
Use the configuration file to configure the mapping between a bucket and a custom domain name. For more information, see Configure ossutil.
Use the sign command to generate a signed URL of an object. For more information, see sign (generate signed object URLs).
Generate a permanent object URL
WarningTo generate a permanent object URL that never expires, you need to set the ACL of the object to public-read. After you set the ACL of an object to public-read, all users on the Internet have access to the object, which may cause data leaks and high OSS bills. We recommend that you use choose temporary URLs over permanent URLs.
To obtain a permeant URL of an object, perform the following steps:
Set the ACL of the object to public-read.
For more information, see Object ACLs.
Generate the object URL by concatenating the custom domain name and object name.
You do not need to include signature information in the URL of a public-read object by using the custom domain name that is mapped to the bucket that contains the object. The URL of a public-read object based on a custom domain name is in the
https://YourDomainName/ObjectName
format.For example, if you map static.example.com to the examplebucket bucket in the China (Hangzhou) region, you can use the
http://static.example.com/demo.png
URL to access the example.jpg in the bucket.
Use the object URL to access the object from a browser.
What to do next
Configure HTTPS access
To use a custom domain name to access the mapped bucket over HTTPS, you need to upload an HTTPS certificate. For more information, see Host SSL certificates.
Use CDN to accelerate access to OSS
You can use Alibaba Cloud CDN to accelerate access to a bucket by mapping the custom domain of the bucket to an accelerated domain name. Access acceleration based on Alibaba Cloud CDN helps improve access speed and stability. For more information, see Map accelerated domain names.
Hotlink protection
To protect a bucket against hotlinking, you can configure a Referer whitelist or blacklist and specify whether to allow requests with an empty Referer header to control access to the bucket. For more information, see Hotlink protection.
Accelerate cross-border data transmission
To improve the speed and stability of cross-border requests, you can map a custom domain name of the bucket to the transfer acceleration domain name of the bucket. For more information, see Map accelerated domain names.
Configure static website hosting
If you want to host a static website in a bucket and use a custom domain name to access the bucket, you need to configure static website hosting. For more information, see Overview.
FAQ
Why did I receive a message indicating that a CNAME record failed to be automatically added because an existing hostname is identical to the hostname used in the CNAME record?
What do I do if the custom domain name is already mapped to another bucket?
What do I do if the NeedVerifyDomainOwnership message is returned for domain mapping?
Why am I unable to preview an object when I use the custom domain name to access the object from a browser?
Can I map a domain name that is connected to WAF and has content?
After a custom domain name is mapped to a bucket, can I use object URLs generated before the mapping to access objects in the bucket?
Does access using a custom domain name mean access over the Internet?
How do I ensure that an object is downloaded when I use the custom bucket domain name to access the object?
How do I unmap a custom domain name?
Related 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 for domain ownership verification, 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 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.