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 in the bucket. Mapping a custom domain name to a bucket does not affect your access to the bucket by using the default domain name.
Prerequisites
A bucket is created. For more information, see Create a bucket.
A root 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.
Domain block bypassing: Some applications or platforms may block default bucket domain names. In this case, 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 makes resource accessing and sharing easier and more user-friendly.
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 downloads. This deceases latency and improves user experience.
URL availability: A custom domain name of a bucket provides a consistent method to access resources in the bucket even if the resources are moved to different paths in the bucket.
Background information
If the default domain name of a bucket or an acceleration endpoint is used to access an object in the bucket, the object is downloaded by default. If a custom domain name is used to access an object in the bucket, a preview is provided by default.
Access using a default domain name or OSS-accelerated domain name
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 for security concerns. The browser detects the Content-Disposition: attachment
header in the response and forcibly downloads the object. The following figure shows the process.
For more information about forcible downloads in access requests that use a default domain name or OSS-accelerated domain name, 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 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 forced download in the response. The browser detects that no value is specified for the Content-Disposition
header in the response and sets the header to inline
by default, which specifies a preview of the object content in the browser instead of an object download. The following figure shows the process.
Limits
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 allow you map a wildcard domain name to a bucket. For example, you cannot map a domain name that starts with the asterisk (*) to a bucket. This wildcard domain name setting causes all subdomains of the domain name to point to the bucket. If you use Alibaba Cloud CDN to accelerate access to a bucket, you can map a wildcard 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 WHOIS.
You can check 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 Names 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 then 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.
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 of the TXT record.
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 Names 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 such as
static.example.com
and click Obtain TXT. Copy the Hostname and Value.ImportantAfter you copy the TXT record, do not close the Map Custom Domain Name panel until you submit the information. If you close the Map Custom Domain Name panel, the value of the TXT record becomes invalid. As a result, 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 tab, 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
Select a DNS line that is used to resolve the domain. 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 Period
Select how long the record is kept in the cache. 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 and click DNS Settings in the Actions column.
On the DNS Settings tab, 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
Specify the hostname based on the 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
Select a DNS line that is used to resolve the domain. 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 domain name 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 Period
Select how long the record is kept in the cache. 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.
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 Names 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 then copy the Hostname and Value.
ImportantAfter you copy 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 value of the TXT record becomes invalid. As a result, the subsequent domain ownership verification fails.
On the DNS platform of your domain provider, use the settings described in the following table to add a TXT record.
Item
Description
Example
Record type
Specify the TXT record type.
TXT
Hostname
Enter the hostname that was recorded earlier.
****59e5-4bbd-aef4-8e401dc13a0a.static
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..
On the DNS platform of your domain provider, use the settings described in the following table to add a CNAME record.
Item
Description
Example
Record type
Specify the CNAME record type.
CNAME
Hostname
Specify the hostname based on the 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 is
static.example.com
, enter static.
static
Value
Enter the public domain name of the bucket. The domain name 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 default bucket domain, 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
Sample success response:
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
Sample success response:
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 objects in the bucket over HTTP.
Upload an object to the bucket.
For more information, see Simple upload.
Obtain object URLs.
Obtain 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 a private object URL that is accessible within the specified period of time. The URL of a private object follows the
http://YourDomain/ObjectName?SignatureInformation
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 other parameters, and then 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, 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 code samples for different programming languages, see Create a signed URL by using signature V1.
Java
// Specify the custom domain name. String endpoint = "yourEndpoint"; // 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 ClientBuilderConfiguration and change the default values of 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\Credentials\EnvironmentVariableCredentialsProvider; use OSS\OssClient; use OSS\CoreOssException; // 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 custom domain name. Example: http://example.com. $endpoint = "http://example.com"; try { $config = array( "provider" => $provider, "endpoint" => $endpoint, "cname" => true ); $ossClient = new OssClient($config); } 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', // 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, cname: true });
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 environment variables are configured. 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 the 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. Before you run the sample code, make sure that the environment variables are configured. provider, err := oss.NewEnvironmentVariableCredentialsProvider() if err != nil { fmt.Println("Error:", err) os.Exit(-1) } // Set yourEndpoint to the custom domain name of the bucket. // Set oss.UseCname to true to enable CNAME. 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 the default bucket name and the custom domain name. For more information, see Configure ossutil.
Use the sign command to generate a signed URL of an object in the bucket. For more information, see sign (generate signed object URLs).
Obtain a permanent object URL
WarningTo obtain 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 can access the object over the Internet, 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 a custom URL of a public-read object. The custom URL of a public-read object is in the
https://YourDomainName/ObjectName
format.For example, the examplebucket bucket in the China (Hangzhou) region contains the example.jpg object and is mapped to static.example.com, the custom URL of the object is
https://static.example.com/example.jpg
.
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 SSL 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 a CDN-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 access, you can map a custom domain name of the bucket to the OSS-accelerated 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 of the bucket to access the bucket, you need to configure static website hosting. For more information, see Overview.
FAQ
What do I do if I receive an error 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 error code 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 a custom domain name use Internet access?
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 that point to domain names of a bucket, see ListCname.
For more information about the API operation that you can call to delete a CNAME record that points to a domain name 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.