Bind the custom domain name to the bucket default domain name
Use Scenarios
Preview Area : For safety reasons, through OSS Default Bucket When the domain name accesses the file, OSS The download response header will be forced to increase, causing the browser to force the download of files. Accessing a file using a custom domain name will not force the addition of a download response header, so that the file can be previewed in the browser. About using OSS Default for Bucket The domain name accesses the file, and triggers the effective time and effective object of the automatic download. See Appendix: Forced Download Hit x-oss-ec rule 。 Visit. apk Or. ipa file : For safety reasons, through OSS default Bucket Domain Access.apk Or. ipa File, OSS Will return four hundred Error, error code is ApkDownloadForbidden . Use a custom domain name to access. apk Or. ipa The file will not be blocked. Brand image and professionalism : Bind custom domain names, enhance brand image and professionalism, and increase user trust. Prevent domain name from being blocked : Bind a custom domain name to prevent the default domain name from being blocked and ensure normal access to resources. Accessibility : Access using a custom domain name OSS Bucket, It is easier to access and share resources. Persistence of links : Bind a custom domain name to ensure link persistence. Resources can still be accessed even if the storage location changes.
Restrictions on use
Binding Chinese domain names is not supported. The domain name is not bound in image processing. Each domain name can only be bound to one Bucket。 each Bucket Can bind at most one hundred Domain names. adopt OSS When the management console binds a custom domain name, it is not allowed to bind a universal domain name (set the domain name prefix to *, so that all sub domain names of the main domain name point to Bucket Default domain name). adopt CDN accelerate OSS It is allowed to bind the universal domain name, but the domain name will not be OSS The management console displays. The top-level domain name involved in the bound custom domain name must meet the requirements of the specified suffix, otherwise it will be regarded as an invalid domain name, which will eventually lead to the domain name binding failure. For more information, see Classification and resolution of top-level domain names 。
prerequisite
already Create storage space 。 already Register domain name . It supports binding non AliCloud registered domain names. If you have not registered a domain name, you can register a domain name on the AliCloud domain name service platform. If the Bucket In mainland China, ensure that the domain name has been filed and the account number has been authenticated. Please refer to ICP Filing process 、 Personal real name authentication 、 Enterprise real name authentication 。
Operation steps
Step 1: Bind a custom domain name
Bind the domain name registered by the current AliCloud account
Sign in OSS Management Console 。 single click Bucket List , and then click Target Bucket name. In the left navigation bar, select Bucket Configuration > Domain name management 。 stay Domain name management Page, click Bind domain name 。 stay Bind domain name Panel, enter a custom domain name without a protocol, such as static.example.com , and then click Confirm Binding 。 add to CNAME Record, the domain name will be customized static.example.com Resolve to bound Bucket The default Internet domain name of. Auto Add stay Bind domain name Panel, opening Automatically add CNAME records 。 After opening, Cloud resolution DNS Will automatically add a CNAME record. Examples are as follows: Add manually If not Bind domain name Panel, opening Automatically add CNAME records , you need to Cloud resolution DNS Console Add one manually CNAME Otherwise, the bound custom domain name will not take effect. Sign in Cloud resolution DNS Console 。 stay Public network DNS analysis > Authoritative domain name resolution , click Resolution Settings 。 single click Add Record , fill in the domain name resolution information. parameter explain Sample value Record Type choice CNAME Record the domain name resolution to another domain name CNAME Host record Fill in the prefix of the domain name to be bound. static Resolve request source The circuit used to resolve the domain name. Suggested choice default , the system will automatically select the best route. default Record value fill in Bucket Internet access domain name of. Bucket The structure of the domain name is <bucketname>.<endpoint> . Internet in different regions Endpoint, See OSS Region and access domain name 。 examplebucket.oss-cn-hangzhou.aliyuncs.com TTL The update cycle of the domain name. Leave the default value. explain take effect TTL There is a certain delay in the time of. Please refer to the actual situation. ten minute single click determine 。 When finished, Cloud resolution DNS There will be a CNAME record. Examples are as follows:
Bind domain names registered with other AliCloud accounts
Using AliCloud B Account, obtaining TXT Recorded host records and recorded values. Sign in OSS Management Console 。 single click Bucket List , and then click Target Bucket name. In the left navigation bar, select Bucket Configuration > Domain name management 。 stay Domain name management Page, click Bind domain name 。 stay Bind domain name Panel, enter the Alibaba Cloud to be bound without a protocol A Custom domain name of the account, such as static.example.com , and then copy the Host record and Record value 。
Using AliCloud A Account, adding TXT record. Sign in Cloud resolution DNS Console 。 In the domain name resolution list, click Resolution Settings 。 single click Add Record , fill in the domain name resolution information. parameter explain Sample value Record Type Select the type that the domain name points to as TXT。 TXT Host record Alibaba Cloud resolution DNS The primary domain name has been automatically filled for you. Therefore, it is not necessary to fill in the main domain name manually. If the main domain name is bound, fill in _dnsauth . For example, the domain name is example.com , fill in _dnsauth 。 If the binding is a subdomain name, fill in _Dnsauth.<domain name prefix> . For example, the domain name is static.example.com , fill in _dnsauth.static 。
_dnsauth.static Resolve request source The circuit used to resolve the domain name. Suggested choice default , the system will automatically select the best route. default Record value Fill in Alibaba Cloud B Account acquired TXT In record CnameToken。 b0d777f7ccddeae93358d908ed59**** TTL The update cycle of the domain name. Leave the default value. explain take effect TTL There is a certain delay in the time of. Please refer to the actual situation. ten minute single click determine 。
Using AliCloud B Account number, at OSS Console Bind domain name Panel, click Verify domain name ownership and bind 。 Using AliCloud A Account, adding CNAME record. In the domain name resolution list, click Resolution Settings 。 single click Add Record , fill in the domain name resolution information. parameter explain Sample value Record Type Select the type that the domain name points to as CNAME。 CNAME Host record Fill in the host record according to the domain name prefix. If it is a primary domain name, for example example.com , Enter @ 。 If it is a sub domain name, enter the prefix of the domain name. For example, the domain name is static.example.com , Enter static。
static Resolve request source The circuit used to resolve the domain name. Suggested choice default , the system will automatically select the best route. default Record value fill in Bucket Internet access domain name of. Bucket The structure of the domain name is <bucketname>.<endpoint> . Internet in different regions Endpoint, See OSS Region and access domain name 。 examplebucket.oss-cn-hangzhou.aliyuncs.com TTL The update cycle of the domain name. Leave the default value. explain take effect TTL There is a certain delay in the time of. Please refer to the actual situation. ten minute single click determine 。
Bind domain names registered with non Alibaba Cloud accounts
In Alibaba Cloud OSS, generate TXT Recorded host records and recorded values. Sign in OSS Management Console 。 single click Bucket List , and then click Target Bucket name. In the left navigation bar, select Bucket Configuration > Domain name management 。 stay Domain name management Page, click Bind domain name 。 stay Bind domain name Panel, enter the domain name registered with other domain name service providers without agreement, such as static.example.com , and then copy the Host record and Record value 。
In the domain name service provider's DNS Analytic platform, please refer to the table below to add TXT record. parameter explain Sample value Record Type Select the type that the domain name points to as TXT。 TXT Host record If another domain name service provider's DNS The resolution platform has automatically filled in the main domain name for you. When filling in, you do not need to manually fill in the main domain name. If the main domain name is bound, fill in _dnsauth . For example, the domain name is example.com , fill in _dnsauth 。 If the binding is a subdomain name, fill in _Dnsauth.<domain name prefix> . For example, the domain name is static.example.com , fill in _dnsauth.static 。
_dnsauth.static Record value Fill in from AliCloud OSS Acquired TXT In record CnameToken。 b0d777f7ccddeae93358d908ed59**** In Alibaba Cloud OSS Console Bind domain name Panel, click Verify domain name ownership and bind 。 In the domain name service provider's DNS Analytic platform, please refer to the table below to add CNAME record. parameter explain Sample value Record Type Select the type that the domain name points to as CNAME。 CNAME Host record Fill in the host record according to the domain name prefix. If it is a primary domain name, for example example.com , Enter @ 。 If it is a sub domain name, enter the domain name prefix. For example, the domain name is static.example.com , Enter static。
static Record value fill in Bucket Internet access domain name of. Bucket The structure of the domain name is <bucketname>.<endpoint> . Internet in different regions Endpoint, See OSS Region and access domain name 。 examplebucket.oss-cn-hangzhou.aliyuncs.com
Step 2: Verify the custom domain name
nslookup
nslookup -type=CNAME static.example.com
dig
dig CNAME static.example.com
Step 3: Use a custom domain name
Get pre signature URL。 use OSS Console Sign in OSS Management Console 。 single click Bucket list , and then click Target Bucket name. In the left navigation bar, select 。 On the file list page, click the target file name. stay details Panel Own domain name , select the bound custom domain name, keep the other default values, and then click Copy File URL 。
Use graphical management tools ossbrowser ossbrowser support Object Level operations are similar to those supported by the console. Please follow ossbrowser Interface guidance is completed to obtain pre signature URL Operation of. How to download ossbrowser, See Graphical management tool Ossbrowser 2.0 (preview version) 。 Log in with a custom domain name ossbrowser。
get files URL。
Using AliCloud SDK New using custom domain name OssClient And generate pre signature URL。 Java import com.aliyun.oss.*; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.common.comm.SignVersion; import com.aliyun.oss.model.GeneratePresignedUrlRequest; import java.net.URL; import java.util.Date; public class Demo { public static void main(String[] args) throws Throwable { // yourCustomEndpoint Please fill in your custom domain name. for example http://static.example.com 。 String endpoint = "yourCustomEndpoint"; //Please fill in the Region Information, such as cn-hangzhou String region = "cn-hangzhou"; //Fill in Bucket Name, for example examplebucket。 String bucketName = "examplebucket"; //Fill in Object Full path, such as exampleobject.txt。 Object The full path cannot contain Bucket name. String objectName = "exampleobject.txt"; //Get access credentials from environment variables. Please configure the environment variables before running this code example EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); //Create OSSClient example. //When OSSClient When the instance is no longer used, call shutdown Method to free resources. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); //Note that the settings true open CNAME option clientBuilderConfiguration.setSupportCname(true); //Explicitly declare using the V4 signature algorithm clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { //Specify the generated pre signature URL Expiration time, in milliseconds. This example sets the expiration time to one For example, hours. Date expiration = new Date(new Date().getTime() + 3600 * 1000L); //Generate pre signature URL。 GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.GET); //Set expiration time. request.setExpiration(expiration); //Via HTTP GET Request to generate pre signature URL。 URL signedUrl = ossClient.generatePresignedUrl(request); //Print pre signature URL。 System.out.println("signed url for getObject: " + signedUrl); } 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 #Get access credentials from environment variables. Before running this code example, make sure that the environment variable has been set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET。 auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider()) #Fill in Endpoint Corresponding Region Information, such as cn-hangzhou。 be careful, v4 Under signature, this parameter must be filled in region = "cn-hangzhou" #Fill in the custom domain name, for example static.example.com。 endpoint = ' http://static.example.com ' # yourBucketName Fill in the name of the storage space. bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region, is_cname=True) #Fill in Object Full path, such as exampledir/exampleobject.txt。 Object The full path cannot contain Bucket name. object_name = 'exampledir/exampleobject.txt' #Generate pre signature of downloaded files URL, Valid for six hundred Seconds. #Generate pre signature URL When, OSS By default Object The forward slash (/) in the full path is escaped, resulting in the generated pre signature URL It cannot be used directly. #Settings slash_safe by True,OSS No Object The forward slash (/) in the full path is escaped, and the generated pre signature URL It can be used directly. url = bucket.sign_url('GET', object_name, 600, slash_safe=True, params=params) Print ('pre signature URL The address of is: ', url) Node.js const OSS = require("ali-oss"); //Define a function to generate a pre signed URL async function generateSignatureUrl(fileName) { //Get pre signature URL const client = await new OSS({ //Use custom domain name as Endpoint。 endpoint: ' http://static.example.com ', //Get access credentials from environment variables. Before running this code example, make sure that the environment variable has been set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET。 accessKeyId: process.env.OSS_ACCESS_KEY_ID, accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET, bucket: 'examplebucket', // yourregion fill in Bucket Location. East China 1 (Hangzhou) as an example, Region Fill in as oss-cn-hangzhou。 region: 'oss-cn-hangzhou', authorizationV4: true, cname: true }); return await client.signatureUrlV4('GET', 3600, { Headers: {}//Please set the request header here according to the actual sent request header }, fileName); } //Call the function and pass in the file name 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; //Get access credentials from environment variables. Before running this code example, make sure that the environment variable has been set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET。 $provider = new EnvironmentVariableCredentialsProvider(); // yourEndpoint fill in Bucket Corresponding to the region Endpoint。 East China 1 (Hangzhou) as an example, Endpoint Fill in as http://static.example.com 。 $endpoint = " http://static.example.com "; //Fill in Bucket name. $bucket= "examplebucket"; //Filling does not include Bucket Name included Object Full path. $object = "exampleobject.txt"; //Specify pre signature URL Expires on 600s (up to 32400s)。 $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 pre signature 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" ) //Defining Global Variables var ( Region string//Storage area BucketName string//The name of the storage space ObjectName string//Object name ) // init Function to initialize command line parameters func init() { flag.StringVar(®ion, "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() { //Resolve command line parameters flag.Parse() //Check bucket Whether the name is empty if len(bucketName) == 0 { flag.PrintDefaults() log.Fatalf("invalid parameters, bucket name required") } //Check region Is it empty if len(region) == 0 { flag.PrintDefaults() log.Fatalf("invalid parameters, region required") } //Check object Whether the name is empty if len(objectName) == 0 { flag.PrintDefaults() log.Fatalf("invalid parameters, object name required") } //Load the default configuration and set the credential provider and region cfg := oss.LoadDefaultConfig(). WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()). WithRegion(region). WithEndpoint(" http://static.example.com "). WithUseCName(true) //Create OSS client client := oss.NewClient(cfg) //Build GetObject Pre signature of URL result, err := client.Presign(context.TODO(), &oss.GetObjectRequest{ Bucket: oss.Ptr(bucketName), Key: oss.Ptr(objectName), //RequestPayer: oss.Ptr("requester"), //Specify the identity of the 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 { //Use pre signature when the returned result contains pre signature header URL send out GET The request also contains the corresponding request header to avoid inconsistency, which may lead to request failure and pre signature error log.Printf("signed headers:\n") for k, v := range result.SignedHeaders { log.Printf("%v: %v\n", k, v) } } } Using Command Line Tools ossutil Use a custom domain name through Presign URL) Pre signature of command generation file URL。 ossutil presign oss://examplebucket/exampleobject.txt --endpoint " http://static.example.com ” --addressing-style "cname" if need ossutil The command automatically uses the custom domain name, instead of manually specifying the custom domain name in the command each time, you can use the configuration file Add a custom domain name in, Access pre signature in browser URL。
relevant API
About Creating Domain Name Ownership Verification Required CnameToken , see CreateCnameToken 。 About Getting Created CnameToken , see GetCnameToken 。 About for a Bucket Bind the interface of the custom domain name, see PutCname 。 About Querying a Bucket See ListCname 。 About deleting a Bucket For the interface of the bound custom domain name, see DeleteCname 。 About using AliCloud resolution DNS add to TXT Resolution record or CNAME For the interface of parsing records, see AddDomainRecord - add resolution records according to the passed in parameters 。
Subsequent operations
adopt HTTPS Protocol Access OSS file
Use long-term valid without signature URL visit OSS file
Set the file as public read : Set the permissions of OSS files to public read. In this case, the URL of the file will not be valid, and anyone can access it. To prevent files from being stolen by other websites, you need to configure them in OSS Anti-theft chain 。 CDN accelerate OSS resources : Keep OSS file permissions private and provide public read access through CDN. In this case, the URL of the file will not be valid, and anyone can access it. To prevent files from being stolen by other websites, you need to configure them on the CDN Anti-theft chain 。
prevent OSS Files are stolen by other websites
use OSS Hosting static websites
promote OSS File download speed in different regions
promote OSS Long distance file transmission speed