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 you want to preview an object 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. If you map a custom domain name to a bucket, you can still use the default domain name to access the bucket.
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 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 if the bucket to which you want to map the domain name resides in the Chinese mainland and real-name verification is complete for your Alibaba Cloud account. For more information about how to apply for an ICP filing for your domain name and complete real-name verification for your Alibaba Cloud account, see Overview and FAQ about real-name registration on the Alibaba Cloud international site (alibabacloud.com).
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 the 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 decreases 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 OSS-accelerated domain name 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 by using the default domain name or an 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 to ensure security. 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 the default domain name or an OSS-accelerated domain name, see Appendix: x-oss-ec rules triggered for forcible download.
Access by 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 forcible 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
, which specifies a preview of the object content in the browser instead of an object download. The following figure shows the process.
Limits
You cannot map a custom domain name that contains Chinese characters to a bucket.
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 to map a wildcard domain name to a bucket. For example, you cannot map a domain name that starts with an asterisk (*) to a bucket. If you map a domain name that starts with an asterisk (*) to a bucket, 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 for 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 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:
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, such as
static.example.com
, and click Confirm.Turn on Automatically Add CNAME Record.
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 by using another Alibaba Cloud account
To map a custom domain name that is registered by 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 copy the Hostname and Record 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 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 by using Alibaba Cloud Account B.
_dnsauth
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 CnameToken of the TXT record that was recorded earlier by using Alibaba Cloud Account B.
b0d777f7ccddeae93358d908ed59****
TTL Period
Select the update interval of the record. Keep the default value.
NoteThere is a certain delay before the TTL setting takes effect.
10 Minutes
Click OK.
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.
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 subdomain 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 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 Period
Select the update interval of the record. 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 by using an Alibaba Cloud account
To map a custom domain name that is registered with another domain registrar, 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, such as
static.example.com
, and copy the Hostname and Record 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 TXT record becomes invalid. As a result, the subsequent domain ownership verification fails.
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
Select TXT.
TXT
Hostname
Enter the hostname obtained from OSS based on the requirements of the DNS platform of your domain registrar.
_dnsauth
Value
Enter the CnameToken of the TXT record that was recorded earlier from OSS.
b0d777f7ccddeae93358d908ed59****
Return to the Map Custom Domain Name panel in the OSS console. Click Verify Domain Name Ownership.
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
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 subdomain is
static.example.com
, enter static.
static
Value
Enter 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 domain name mapping
After you map the custom domain name to the default bucket domain, run 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 effect, you can use the custom domain name to access objects in the bucket over HTTP.
The HTTP protocol cannot ensure the security of data during transmission. Data may be intercepted or tampered with by a third party. To enhance data security, we strongly recommend that you use the HTTPS protocol to access objects in the bucket. For more information, see Configure HTTPS access.
Upload an object to the bucket.
For more information, see Simple upload.
Obtain the URL of the object.
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.
The private object URL is in the following format:
http://YourDomain/ObjectName?signature parameters
. You can use one of the following methods to obtain the private object URL and specify the validity period of the URL:
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 a custom domain name to create an OSSClient instance.
Use the OSSClient instance to call the GeneratePresignedUrl operation to obtain the signed URL of the object.
For the sample code for different programming languages, see Include a V1 signature in a URL.
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 the 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 and modify the default parameters based on your requirements. var conf = new ClientConfiguration(); // Specify that a CNAME can be used as an endpoint to create the OssClient instance. 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 the 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 aos_string_t. */ 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 Specify a custom domain name.
Run the sign command to generate the signed URL of an object in the bucket. For more information, see sign.
Obtain a permanent object URL
WarningTo obtain a permanent object URL that never expires, 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 temporary URLs.
To obtain a permanent 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. The URL of a public-read object is in the following format:
http://YourDomainName/ObjectName
.For example, the examplebucket bucket in the China (Hangzhou) region contains the example.jpg object and is mapped to static.example.com, the 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
The HTTPS protocol integrates the SSL and TLS protocols based on HTTP, which provides strong encryption protection for data transmission. To use a custom domain name to access the objects in the mapped bucket over HTTPS, you must purchase an SSL certificate and host the SSL certificate in OSS. For more information, see Host a certificate for a custom domain name.
Use Alibaba Cloud 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 the access speed and stability. For more information, see Map accelerated domain names.
Configure 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 manage 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 website, 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?
NeedVerifyDomainOwnership
Why am I unable to preview an object when I use a 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?
Is access by using a custom domain name the same as access over the Internet?
How do I ensure that an object is downloaded when I use a 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 the 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.