Accelerate OSS access with CDN

更新时间:
复制 MD 格式

Alibaba Cloud CDN accelerates Object Storage Service (OSS) using a global, distributed cache. When delivering static resources from OSS (such as images, audio, video, and documents) to users worldwide, you can use Alibaba Cloud CDN to significantly improve access speed, reduce latency, and lower traffic costs.

How it works

CDN accelerates access to OSS by using a distributed caching architecture. This architecture caches static content from an OSS bucket (the origin) on globally distributed CDN edge nodes. Serving content from the node closest to the user minimizes latency.

  1. Request routing: When a user requests a resource for the first time, intelligent DNS resolution routes the request to the nearest CDN node with the best network performance.

  2. Origin fetch: If the CDN node detects that the resource is not in its local cache, it sends an origin-fetch request to the OSS origin.

  3. Caching: After OSS returns the content, the CDN node caches the resource according to predefined caching rules and returns it to the user.

  4. Cache hit: For subsequent requests for the same resource, the CDN node serves the content directly from its cache, which eliminates the need for an origin-fetch request. This process shortens the access path, reduces network latency, and decreases origin load, which in turn accelerates access.

Quick start

Prerequisites

  • You have a registered domain, or you can purchase a new domain. Domains that are not registered with Alibaba Cloud are also supported.

  • If your acceleration region includes the Chinese mainland, your domain must have an ICP filing.

Step 1: Add a domain and configure an origin

  1. Go to the CDN console and click Add Domain Name.

  2. Select an Region and a Business Type, and then enter the Domain Name to Accelerate. The accelerated domain can be a root domain (such as example.com) or a custom subdomain (such as oss.example.com). We recommend that you use a subdomain for easier management and scalability.

  3. Click Add Origin. For Origin Information, select OSS Domain, choose the domain name of your target bucket, and then click OK to add the origin server.

  4. Click Next to finish adding the accelerated domain.

After you add the accelerated domain, you can follow the Recommended Configuration wizard to set up basic configurations such as the cache expiration time, range requests to origin, and HTTPS certificates. Alternatively, you can click Skip, Configure Later to proceed directly to the CNAME configuration.

Step 2: Configure a CNAME record

Add a CNAME record in your DNS settings to map the accelerated domain to the CNAME address assigned by CDN. This routes user requests to CDN edge nodes. The following example shows how to configure a CNAME record in the Alibaba Cloud DNS console.

  1. Go to the DNS console. In the Actions column of your target domain, click Settings.

  2. Click Add Record and enter the following information. You can keep the default values for other settings.

    Parameter

    Description

    Record Type

    Select CNAME.

    Hostname

    Enter @ for the root domain or the prefix for the subdomain (such as oss), based on your accelerated domain.

    Record Value

    Enter the CNAME value provided on the wizard page or the accelerated domain list page, such as oss.example.com.w.cdngslb.com.

  3. Click OK and follow the on-screen instructions to add the record.

Note

DNS record propagation time depends on its Time-to-Live (TTL) setting. Full propagation can take from several minutes to several hours. The domain may be inaccessible immediately after configuration. Wait for the DNS record to propagate or try clearing your local DNS cache.

Step 3: Configure private bucket back-to-origin

By default, new buckets are private. To let CDN access a private bucket, enable the private bucket back-to-origin feature. If your bucket has public-read permissions, CDN can access it directly, and you do not need to enable this feature.

  1. In the CDN console, click the target domain. In the left-side navigation pane, click Origin Fetch.

  2. In the Alibaba Cloud OSS Private Bucket Access section, enable the feature. For Origin type, select Same-account back-to-origin.

Important

Enabling private bucket back-to-origin authorizes CDN to access your private bucket and automatically adds signature information to back-to-origin requests. Therefore, clients must use a URL without signature parameters, such as http://example.com/example.jpg. If the URL includes signature parameters such as Expires or Signature, OSS authentication fails and a 403 error is returned.

Step 4: Verify acceleration

After the configuration is complete, run a comparison test to verify the performance improvement for the accelerated domain.

  1. Get the file access URLs:

    URL type

    Method

    Default OSS access URL

    Go to the Bucket List and select your target bucket. For the target file, click View Details in the Actions column, and then click Copy Object URL.

    CDN-accelerated access URL

    Construct the URL by using the accelerated domain and the filename, such as http://example.com/example.jpg (without signature parameters).

  2. Verify the acceleration: Use a speed testing tool or platform, such as the CloudMonitor Disposable Detection Tool, to compare the loading times of the two URLs for the same file.

    Note

    The acceleration effect may not be obvious during the first test because the CDN node needs to fetch the resource from the origin server. Wait for the resource to be cached on the CDN node and then test again.

  3. Check the cache hit status: Use your browser's developer tools (F12) to inspect the value of the X-Cache field in the response header:

    Value

    Description

    Starts with HIT

    Indicates a cache hit. The request was served from the CDN cache, and access was accelerated.

    Starts with MISS

    Indicates a cache miss. The request was not served from the CDN cache and was forwarded to the OSS origin server to retrieve the resource.

Use cases

Video and large file acceleration

Ensuring a good user experience for video-on-demand (VOD) and large file downloads requires special configurations.

Required configurations

  1. Enable Range GETs: Enable Range-based origin fetch for your accelerated domain name. This allows CDN edge nodes to request large files in chunks, which supports video scrubbing and resumable downloads.

  2. Configure a suitable cache TTL: Video files are typically updated infrequently. Set a long cache TTL, such as 30 days or more, to reduce frequent origin fetches.

  3. Use resource prefetch: Before you release a video, use the CDN Refresh and Prefetch Resources feature to distribute the video to edge nodes.

Video bitrate recommendations

Video loading speed is closely related to bitrate. If users report that video playback stutters or is choppy, check the video bitrate:

Bitrate range

Use case

Description

500–2,000 kbps

Mobile devices, standard definition

Recommended range for smooth loading.

2,000–4,000 kbps

PCs, high definition

Requires sufficient user bandwidth.

>6,000 kbps

Ultra-high definition (UHD)/4K

May cause slow loading. Provide multiple bitrate versions.

Note

If the video bitrate is too high (greater than 10 Mbps), loading may be slow even with CDN acceleration. Use the video transcoding service to reduce the bitrate or provide adaptive bitrate streaming.

Multi-bucket origin configuration

If your architecture uses multiple OSS buckets for different resource types, use one of the following methods to configure multi-source origin fetch.

Method 1: Separate subdomain architecture

Assign separate, semantic subdomains to buckets for different features or resource types, and then configure CDN acceleration for each subdomain individually.

Resource type

Example subdomain

Recommended configuration

Image resources

img.example.com

Configure a long-term cache policy to improve access speed.

Audio and video resources

video.example.com

Enable Range-based origin fetch to support resumable downloads.

Sensitive documents

docs.example.com

Independently enable URL authentication to ensure security.

Using a separate subdomain architecture provides the following benefits:

  • Semantic subdomains are easy for development teams to identify and maintain.

  • Traffic is distributed at the DNS level, which avoids the concurrent connection limits of a single domain.

  • Each bucket can have its own cache policies, security configurations, and monitoring alerts.

  • Independent monitoring helps you pinpoint performance bottlenecks and abnormal traffic.

Method 2: Unified domain with path-based routing

To provide a unified access point for buckets from different services, configure a single accelerated domain name and use the rules engine to route requests to specific buckets based on the request path. This example shows how to configure the accelerated domain name oss.example.com to fetch content from two buckets: cdn-bucket1 and cdn-bucket2.

  1. Add origin information: Add cdn-bucket1 and cdn-bucket2 to the Origin Information of the accelerated domain name, and then configure CNAME resolution for the domain.

  2. Add path rules: For the accelerated domain name, go to Add Rule to create two URL path rules that match http://oss.example.com/bucket1/* and http://oss.example.com/bucket2/* respectively.

    Rule name

    Type

    Match operator

    Match value

    bucket1 (customizable)

    URI

    Contains any of

    /bucket1/*

    bucket2 (customizable)

    URI

    Contains any of

    /bucket2/*

  3. Add conditional origins: In Basics, use the Add Conditional Origin option to associate path rules with their corresponding origins.

    Rule Condition

    Origin Address

    bucket1

    cdn-bucket1.oss-<region-id>.aliyuncs.com

    bucket2

    cdn-bucket2.oss-<region-id>.aliyuncs.com

  4. Specify the origin Host header: In the Origin Fetch, use the Specify Origin HOST option to ensure that origin fetch requests are correctly routed to the target bucket.

    Origin Server Type

    Origin Address

    Origin HOST type

    Origin Host

    Rule Condition

    Primary Origin Address

    cdn-bucket1.oss-<region-id>.aliyuncs.com

    Primary Origin Domain

    cdn-bucket1.oss-<region-id>.aliyuncs.com

    bucket1

    Primary Origin Address

    cdn-bucket2.oss-<region-id>.aliyuncs.com

    Primary Origin Domain

    cdn-bucket2.oss-<region-id>.aliyuncs.com

    bucket2

  5. Rewrite the origin URL: In the Origin Fetch, add a rule to Origin Path Rewrite. This rule strips the virtual path (such as /bucket1) during an origin fetch to match the object's actual storage path.

    Path to Be Rewritten

    Target Path

    Flag

    ^/bucket1/(.*)$

    /$1

    break

    ^/bucket2/(.*)$

    /$1

    break

  6. Verify the configuration: After completing the configuration, you can use the single accelerated domain name to access resources from different OSS buckets based on the path. For example, a request to http://oss.example.com/bucket1/example.jpg fetches the example.jpg file from the root directory of the cdn-bucket1 bucket.

Cross-account private origin fetch

If you need to fetch content from a private bucket in another account (for example, using an accelerated domain name in Account A to access a bucket in Account B), you can enable Alibaba Cloud OSS Private Bucket Access for your accelerated domain name and select the cross-account option.

  1. Add the cross-account bucket as an origin: When adding origin information for a new accelerated domain name, select Custom OSS Origin and enter the domain name of the target bucket.

  2. Enable cross-account private origin fetch: In the Origin Fetch for the accelerated domain name, enable Alibaba Cloud OSS Private Bucket Access. For Type, select Cross-account or Same-account Origin Fetch, and then enter the AccessKey ID and AccessKey Secret of an account with permission to access the target bucket.

Deploy to production

Best practices

Secure transit: Enable HTTPS

To encrypt data transmission between clients and CDN nodes, configure an HTTPS certificate for your accelerated domain name and enable forced HTTPS redirection. HTTPS not only prevents data from being stolen or tampered with in transit but also avoids browser security warnings, which enhances user trust and brand image.

Certificate configuration locations

Access method

Configuration location

Description

Direct access to an OSS domain name

OSS console

In the Bucket Settings > Domain Names section of your bucket.

Access through a CDN accelerated domain name

CDN console

In the HTTPS section for the accelerated domain name.

Note
  • A wildcard certificate, such as *.example.com, only matches second-level subdomains. You must apply for a separate certificate for third-level subdomains, such as img.cdn.example.com.

  • OSS does not support the HTTP/2 protocol. To use HTTP/2, you must accelerate access through CDN.

Performance optimization: Configure cache policy

Cache policies are critical to CDN performance and should cover both cache duration and parameter handling.

Set cache expiration

Maximize your cache hit ratio by configuring CDN cache expiration rules:

Type

Recommended cache duration

Description

Infrequently updated static files (images, audio, video, installation packages)

1 month or longer

Reduces unnecessary origin requests.

Frequently updated static files (JS, CSS)

Several hours to several days

Manage updates with versioning (for example, style.v1.1.css).

Dynamic files or APIs (PHP, JSP)

0 seconds (do not cache)

Ensures the latest content is fetched for every request.

Configure parameter handling to enable Image Processing

OSS Image Processing, which includes features like resizing, cropping, and watermarking, is frequently used. By default, CDN filters all parameters to maximize the cache hit ratio, which disables Image Processing directives such as ?x-oss-process. To use this feature, you must modify the parameter filtering settings in the Optimization section for your accelerated domain name in the CDN console.

Scenario

Parameter filtering

Description

Purely static resource distribution

Filter All Parameters

Maximizes the cache hit ratio.

Using OSS Image Processing

Retain All Parameters or Retain Specified Parameter: x-oss-process

Ensures Image Processing directives take effect.

Versioned resources

Retain Specified Parameter: v or version

Supports cache updates based on version numbers.

Availability: Use prefetch and auto-refresh

After you enable caching, updates to origin files are not immediately propagated to CDN edge nodes. Use the following strategies:

  • Prefetch: Before a new release or promotional event, use the CDN Refresh and Prefetch Resources feature to distribute popular resources to edge nodes worldwide. This prevents a surge of origin requests from overwhelming your origin at launch.

  • Automatic cache refresh: In your bucket's Bucket Settings > Domain Names section, enable automatic CDN cache refresh for the bound domain. When you update an OSS file by using an API, OSS automatically triggers a CDN refresh task.

Note

Automatic cache refresh is effective only when the CDN service and the OSS bucket belong to the same Alibaba Cloud account. It does not guarantee immediate updates. For time-sensitive scenarios, we recommend that you manually refresh the cache by using the CDN refresh feature after updating files.

Cross-origin access: Configure a CORS policy

When a front-end application needs to make cross-origin requests to OSS resources accelerated by CDN, CORS rules configured only on the OSS bucket may not work due to CDN caching. The best practice is to configure CORS-related response headers directly at the CDN level:

  1. In the CDN console, click the accelerated domain name or click Manage in the Actions column.

  2. In the Cache > Modify Outgoing Response Header tab, configure the response header parameters and values.

    Response Header

    Header Value

    CORS

    Access-Control-Allow-Origin

    *

    Enable

    Access-Control-Allow-Methods

    POST, GET, HEAD, PUT, DELETE

    Not applicable

    Access-Control-Max-Age

    3600

    Not applicable

    Note

    The parameter settings are for reference only. Adjust them based on your actual business scenario.

Performance optimization: Improve large file and data transfer

  • Enable Range back-to-origin: For scenarios like video on demand and large file distribution, it is crucial to configure Range back-to-origin. This feature lets CDN nodes request large files in chunks, enabling advanced features like video scrubbing and significantly reducing origin traffic and first-screen latency.

  • Optimize data transfer: To reduce the transfer size of text-based files like JS, CSS, and HTML, you can enable Gzip compression or Page Optimization in the CDN console.

Note
  • Enabling Page Optimization or Gzip compression changes the Content-Length and Content-MD5 values of a file. If your application logic relies on these values for verification, use these features with caution.

  • If you enable both Page Optimization and Gzip compression, only Gzip compression takes effect.

Smooth rollout: Zero-downtime domain switch

When switching your existing service from an OSS bucket domain to an accelerated domain name, adopt a phased approach:

  1. Preparation phase: Complete all configurations for the accelerated domain name and thoroughly test its functionality and performance in a staging environment.

  2. Canary release phase (recommended during off-peak hours): Use a canary release to switch a portion of your traffic to the accelerated domain name, gradually increasing the volume to mitigate risks.

  3. Verification phase: Closely monitor access logs and error rates. Analyze key metrics such as response time and success rate to ensure the service is functioning normally.

  4. Full release phase: After thorough verification, switch all traffic to the accelerated domain name.

  5. Rollback plan: If issues occur, immediately roll back to the bucket domain, analyze the root cause, and then redeploy.

Risk prevention

Hotlink protection: Configure Referer and URL authentication

To prevent unauthorized websites from hotlinking your resources, which can lead to unnecessary traffic costs and bandwidth consumption, you must configure security policies:

  • Referer-based hotlink protection: Configure a Referer whitelist or blacklist to allow access only from specified domains by validating the Referer field in the HTTP request header.

  • URL authentication: For a private OSS bucket, enabling private bucket back-to-origin authorizes CDN nodes to access it. This means private resources that previously required a signature can be publicly accessed through the CDN domain. To restore security control over these resources, configure URL authentication at the CDN level.

Note

After you enable CDN acceleration, hotlinking requests may hit the CDN cache directly without going to the origin, thereby bypassing OSS hotlink protection. To ensure protection is effective, you must also configure hotlink protection rules at the CDN level.

Monitor traffic anomalies

Create an alert rule for your accelerated domain name in Cloud Monitor to promptly detect abnormal spikes in CDN traffic.

Origin security: Configure SNI and host

Ensuring stable and secure communication between CDN and OSS is critical for service availability.

Configure back-to-origin SNI

To prevent origin requests without Server Name Indication (SNI) from causing access issues with OSS, you must configure the default back-to-origin SNI in CDN. Set the SNI to match the back-to-origin host, which defaults to the accelerated domain name. When an origin request includes an SNI, OSS can identify the business domain during the TLS handshake and return the matching certificate. If OSS receives a request without an SNI, it cannot accurately identify the business domain and may trigger stricter traffic limits.

Hide origin information

By default, CDN uses the bucket domain for origin requests. If an origin error occurs, such as a file not being found, the error message may expose the OSS bucket domain, which is a security risk. To hide this information, change the back-to-origin host to the accelerated domain name:

  1. On the Buckets page, click the target bucket. Then, in the Bucket Settings > Domain Names section, bind the accelerated domain name to the bucket.

  2. In the CDN console, click the target accelerated domain name. Then, in the Origin Fetch > Default Origin Host section, click Modify and change the Domain Type to CDN Domain.

Auditing and troubleshooting: Enable access logs

A production environment must have comprehensive logging capabilities for security audits, performance analysis, and troubleshooting. Configure real-time log delivery in the CDN console to send access logs to Log Service. You can use Log Service to perform in-depth analysis and set up alerts for access behavior, traffic distribution, popular resources, and request errors.

Billing

Fee type

Description

CDN fees

Configuring CDN to accelerate access to OSS incurs CDN traffic fees. For details, see CDN billing overview.

OSS fees

When a CDN node experiences a cache miss, it pulls resources from OSS, incurring charges for CDN origin-pull egress traffic. For details, see CDN origin-pull egress traffic.

FAQ

5xx errors during CDN back-to-origin

A 5xx error indicates that CDN cannot retrieve resources from the OSS origin server. To troubleshoot, check the following:

Aspect

Description

Origin server configuration

Verify that the OSS origin server address configured in the CDN console is correct.

Back-to-origin protocol

If CDN is configured for HTTPS back-to-origin or follow-protocol back-to-origin, ensure the origin server supports HTTPS and has a correctly configured SSL certificate.

Network connectivity

Test the network connectivity from a CDN node or your local machine to the OSS origin server. CDN nodes are public, so the origin server must be publicly accessible.

Origin server load

On the CDN Real-time Monitoring page, check for sudden spikes in bandwidth and traffic. For frequently accessed resources, you should prefetch the resources and set a reasonable cache expiration rule.

403 error for static websites with CDN

Cause: This issue typically occurs when you enable CDN acceleration for a private bucket that is configured for static website hosting. The root cause is a conflict between two access mechanisms:

  • For back-to-origin requests to a private bucket, CDN includes an authentication signature.

  • The default index page feature of OSS static website hosting (for example, returning index.html when / is accessed) requires an anonymous request.

When a user accesses the root directory of the accelerated domain, CDN sends a signed request to the bucket's root directory. OSS does not trigger the static website hosting logic for signed requests. Instead, it attempts to perform a ListObjects operation, which results in a 403 error.

Solution: Bypass the OSS static website hosting mechanism and achieve the same behavior by configuring a url rewrite rule in CDN:

Parameter

Value

Path to Be Rewritten

^/$ (matches root path access)

Target Path

/index.html (or your actual homepage file name)

Flag

Redirect

Uploading files through a CDN domain

For security reasons, we do not recommend uploading files to OSS through a CDN domain name. If CDN is configured for public write access, anyone can upload files to OSS without authentication, which makes your bucket vulnerable to malicious uploads and data tampering. We recommend that you upload files using an OSS domain name and apply the principle of least privilege.

Reduced OSS traffic with CDN

Yes. If CDN-cached files have a high cache hit ratio, OSS outbound traffic will decrease significantly, reducing your OSS traffic costs.

This works best in scenarios where the same data is accessed repeatedly, such as website visits, image downloads, and game distribution. The higher the cache hit ratio, the lower the back-to-origin traffic, and the greater the cost savings.

Tracking file access requests

After you enable CDN acceleration, OSS access logs do not record requests served directly from the CDN cache. You can track requests in the following ways:

Data range

Method

Log data from the last 30 days

Download and analyze CDN offline logs.

Log data older than 30 days

After you configure real-time log delivery in CDN, view and analyze the data on the CDN Real-time Log Data Statistics page.

Troubleshooting 403 Forbidden errors

A 403 Forbidden error can be caused by access controls on either OSS or CDN. To identify the source, first try accessing the resource directly via its default OSS domain name.

  • If the request is successful: The issue is on the CDN side. Check CDN configurations such as referer-based hotlink protection, URL authentication, and settings for private bucket back-to-origin.

  • If the request also returns a 403 error: The issue is on the OSS side. Check your OSS configurations, such as Bucket ACL, referer-based hotlink protection, and Bucket Policy.

OSS traffic costs after CDN migration

Possible causes:

  1. Some requests still access OSS directly: Check your application code or third-party integrations for any OSS domain names that have not been replaced with the CDN-accelerated domain name.

  2. Cache misses lead to back-to-origin requests: Each cache miss triggers a back-to-origin request, which generates OSS back-to-origin traffic. Check your CDN cache hit ratio; if it is low, optimize your cache configuration.

  3. A public-read bucket is being accessed maliciously: If your bucket has public-read permissions, it is vulnerable to malicious access. If your business requirements allow, we recommend setting the bucket to private and enabling private bucket back-to-origin in CDN.