使用內容傳遞網路 (CDN) 的最佳作法Best practices for using content delivery networks (CDNs)

內容傳遞網路 (CDN) 是可以有效率地將 Web 內容傳遞給使用者的分散式伺服器網路。A content delivery network (CDN) is a distributed network of servers that can efficiently deliver web content to users. Cdn 會將快取的內容儲存在靠近使用者的邊緣伺服器上,以將延遲降至最低。CDNs store cached content on edge servers that are close to end users to minimize latency.

CDN 通常用來傳遞靜態內容,例如影像、樣式表、文件、檔案、用戶端指令碼和 HTML 頁面。CDNs are typically used to deliver static content such as images, style sheets, documents, client-side scripts, and HTML pages. 使用 CDN 的主要優點是較低的延遲及更快將內容傳遞給使用者,而與裝載應用程式的資料中心的地理位置無關。The major advantages of using a CDN are lower latency and faster delivery of content to users, regardless of their geographical location in relation to the datacenter where the application is hosted. CDN 也有助於降低 Web 應用程式的負載,因為此類應用程式不需要處理對 CDN 所裝載的內容提出的要求。CDNs can also help to reduce load on a web application, because the application does not have to service requests for the content that is hosted in the CDN.

CDN 圖表

在 Azure 中,Azure 內容傳遞網路是一個全域 CDN 解決方案,可提供裝載在 Azure 或任何其他位置中的高頻寬內容。In Azure, the Azure Content Delivery Network is a global CDN solution for delivering high-bandwidth content that is hosted in Azure or any other location. 使用 Azure CDN 可讓您快取從 Azure Blob 儲存體、Web 應用程式、虛擬機器、任何可公開存取的 Web 伺服器載入的公用物件。Using Azure CDN, you can cache publicly available objects loaded from Azure blob storage, a web application, virtual machine, any publicly accessible web server.

本主題說明使用 CDN 時的一般最佳作法和考量事項。This topic describes some general best practices and considerations when using a CDN. 如需詳細資訊,請參閱 Azure CDNFor more information, see Azure CDN.

如何及為何使用 CDNHow and why a CDN is used

CDN 的典型用法包括:Typical uses for a CDN include:

  • 傳遞用戶端應用程式的靜態資源,通常是來自網站。Delivering static resources for client applications, often from a website. 這些資源可以是映像、樣式表、文件、檔案、用戶端指令碼、HTML 頁面、HTML 片段,或伺服器不需要為每個要求修改的任何其他內容。These resources can be images, style sheets, documents, files, client-side scripts, HTML pages, HTML fragments, or any other content that the server does not need to modify for each request. 應用程式可在執行階段建立項目,並讓 CDN 使用它們 (例如,藉由建立目前頭條新聞清單),但它不會為每個要求這麼做。The application can create items at runtime and make them available to the CDN (for example, by creating a list of current news headlines), but it does not do so for each request.

  • 將公用靜態和共用內容傳遞給裝置,例如行動電話和平板電腦。Delivering public static and shared content to devices such as mobile phones and tablet computers. 應用程式本身是一個 Web 服務,可將 API 提供給執行於各種裝置的用戶端。The application itself is a web service that offers an API to clients running on the various devices. CDN 也可以傳遞靜態資料集 (透過 Web 服務) 供用戶端使用,或許用來產生用戶端 UI。The CDN can also deliver static datasets (via the web service) for the clients to use, perhaps to generate the client UI. 例如,CDN 可用來散發 JSON 或 XML 文件。For example, the CDN could be used to distribute JSON or XML documents.

  • 讓用戶端使用僅包含公用靜態內容的整個網站,而不需要任何專用的計算資源。Serving entire websites that consist of only public static content to clients, without requiring any dedicated compute resources.

  • 視需要將視訊檔案串流到用戶端。Streaming video files to the client on demand. 視訊可從提供 CDN 連接的全球資料中心,獲得低延遲和可靠連線的好處。Video benefits from the low latency and reliable connectivity available from the globally located datacenters that offer CDN connections. Microsoft Azure 媒體服務 (AMS) 會與 Azure CDN 整合,直接提供內容給 CDN,以進行進一步的發佈。Microsoft Azure Media Services (AMS) integrates with Azure CDN to deliver content directly to the CDN for further distribution. 如需詳細資訊,請參閱串流端點概觀For more information, see Streaming endpoints overview.

  • 一般可改善使用者體驗,特別是與裝載應用程式的資料中心相距較遠的使用者。Generally improving the experience for users, especially those located far from the datacenter hosting the application. 這些使用者可能會遭遇到較高的延遲。These users might otherwise suffer higher latency. Web 應用程式中的內容大小總計通常是靜態的,而且使用 CDN 有助於維護效能和整體使用者體驗,同時不需要將應用程式部署到多個資料中心。A large proportion of the total size of the content in a web application is often static, and using the CDN can help to maintain performance and overall user experience while eliminating the requirement to deploy the application to multiple datacenters. 如需 Azure CDN 節點位置清單,請參閱 Azure CDN POP 位置For a list of Azure CDN node locations, see Azure CDN POP Locations.

  • 支援 IoT (物聯網) 解決方案。Supporting IoT (Internet of Things) solutions. 如果需要直接將韌體更新散發到每個裝置,與 IoT 解決方案有關的裝置和設備數量極為龐大,可能會輕易導致應用程式無法因應。The huge numbers of devices and appliances involved in an IoT solution could easily overwhelm an application if it had to distribute firmware updates directly to each device.

  • 在不需要調整應用程式的情況下,進行尖峰和激增,而不需要調整應用程式,以避免後續的執行成本增加。Coping with peaks and surges in demand without requiring the application to scale, avoiding the consequent increase in running costs. 例如,針對硬體裝置 (例如特定型號的路由器) 或消費性裝置 (例如智慧型電視) 發行作業系統的更新時,如果數以百萬的使用者和裝置在短期間內下載更新,則可能會視需要產生龐大的尖峰量。For example, when an update to an operating system is released for a hardware device such as a specific model of router, or for a consumer device such as a smart TV, there will be a huge peak in demand as it is downloaded by millions of users and devices over a short period.

挑戰Challenges

計劃使用 CDN 時必須考量幾項挑戰。There are several challenges to take into account when planning to use a CDN.

  • 部署Deployment. 決定 CDN 將從中提取內容的原點,及是否需要將內容部署到多個儲存體系統中。Decide the origin from which the CDN fetches the content, and whether you need to deploy the content in more than one storage system. 請將部署靜態內容和資源的程序納入考量。Take into account the process for deploying static content and resources. 比方說,您可能需要實作個別的步驟,才能將內容載入 Azure blob 儲存體。For example, you may need to implement a separate step to load content into Azure blob storage.

  • 版本控制和快取控制Versioning and cache-control. 考慮如何更新靜態內容和部署新版本。Consider how you will update static content and deploy new versions. 請了解 CDN 執行快取和存留時間 (TTL) 的方式。Understand how the CDN performs caching and time-to-live (TTL). 如需 Azure CDN 的相關資訊,請參閱快取的運作方式For Azure CDN, see How caching works.

  • 測試Testing. 在本機或在預備環境中開發和測試應用程式時,很難為 CDN 設定執行本機測試。It can be difficult to perform local testing of your CDN settings when developing and testing an application locally or in a staging environment.

  • 搜尋引擎最佳化 (SEO)Search engine optimization (SEO). 當您使用 CDN 時,如影像和文件等內容皆由不同的網域服務。Content such as images and documents are served from a different domain when you use the CDN. 這可能會影響此內容的 SEO。This can have an effect on SEO for this content.

  • 內容安全性Content security. 並非所有的 CDN 皆提供任何形式的內容存取控制。Not all CDNs offer any form of access control for the content. 有些 CDN 服務 (包括 Azure CDN) 支援以權杖型驗證保護 CDN 內容。Some CDN services, including Azure CDN, support token-based authentication to protect CDN content. 如需詳細資訊,請參閱使用權杖驗證來保護 Azure 內容傳遞網路資產For more information, see Securing Azure Content Delivery Network assets with token authentication.

  • 用戶端安全性Client security. 用戶端可從不允許存取 CDN 上資源的環境中連接。Clients might connect from an environment that does not allow access to resources on the CDN. 這可能是安全性限制的環境,限制只能存取一組已知來源,或防止從原始頁面以外的任何位置載入資源的環境。This could be a security-constrained environment that limits access to only a set of known sources, or one that prevents loading of resources from anything other than the page origin. 需要後援實作,才能處理這些情況。A fallback implementation is required to handle these cases.

  • 恢復 功能。Resilience. CDN 是應用程式的潛在單一失敗點。The CDN is a potential single point of failure for an application.

CDN 可能較不實用的案例包括:Scenarios where a CDN may be less useful include:

  • 如果內容點擊率偏低,該內容在有效期間 (由其存留時間設定值決定) 可能僅被存取數次。If the content has a low hit rate, it might be accessed only few times while it is valid (determined by its time-to-live setting).

  • 如果資料是私人的,例如適用於大型企業或供應鏈生態系統。If the data is private, such as for large enterprises or supply chain ecosystems.

一般方針和最佳做法General guidelines and good practices

使用 CDN 是最小化應用程式負載,及最大化可用性與效能的好方法。Using a CDN is a good way to minimize the load on your application, and maximize availability and performance. 為應用程式使用的所有適當內容和資源,考慮採用此策略。Consider adopting this strategy for all of the appropriate content and resources your application uses. 設計使用 CDN 的策略時,請考量以下幾節中的要點。Consider the points in the following sections when designing your strategy to use a CDN.

部署Deployment

如果您未在應用程式部署封裝或程序中包含靜態內容,該靜態內容可能需要與應用程式分開佈建和部署。Static content may need to be provisioned and deployed independently from the application if you do not include it in the application deployment package or process. 請思考這會如何影響版本控制方法,也就是您用於管理應用程式元件和靜態資源內容的方法。Consider how this will affect the versioning approach you use to manage both the application components and the static resource content.

請考慮使用統合和縮製技術,以縮短用戶端的載入時間。Consider using bundling and minification techniques to reduce load times for clients. 統合可將多個檔案合併成單一檔案。Bundling combines multiple files into a single file. 縮製可在不變更功能的情況下,從指令碼和 CSS 檔案中移除非必要的字元。Minification removes unnecessary characters from scripts and CSS files without altering functionality.

如果您需要將內容部署到其他位置,這會是部署程序中的額外步驟。If you need to deploy the content to an additional location, this will be an extra step in the deployment process. 如果應用程式更新 CDN 的內容 (或許是固定間隔或為了回應事件),它必須將更新的內容儲存於任何其他位置,以及 CDN 的端點。If the application updates the content for the CDN, perhaps at regular intervals or in response to an event, it must store the updated content in any additional locations as well as the endpoint for the CDN.

請考量在預期 CDN 會提供部分靜態內容時,您應如何處理本機開發和測試。Consider how you will handle local development and testing when some static content is expected to be served from a CDN. 例如,您可以將內容預先部署到 CDN 作為組建腳本的一部分。For example, you could predeploy the content to the CDN as part of your build script. 或者,您可以使用編譯指示詞或旗標,控制應用程式載入資源的方式。Alternatively, use compile directives or flags to control how the application loads the resources. 例如,在偵錯模式中,應用程式可能會從本機資料夾載入靜態資源。For example, in debug mode, the application could load static resources from a local folder. 在發行模式中,應用程式會使用 CDN。In release mode, the application would use the CDN.

請考慮使用檔案壓縮的選項,例如 gzip (GNU zip)。Consider the options for file compression, such as gzip (GNU zip). 壓縮可在來源伺服器上由裝載的 Web 應用程式執行,或是直接在邊緣伺服器上由 CDN 執行。Compression may be performed on the origin server by the web application hosting or directly on the edge servers by the CDN. 如需詳細資訊,請參閱在 Azure CDN 中壓縮檔案以改善效能For more information, see Improve performance by compressing files in Azure CDN.

路由和版本控制Routing and versioning

您可能需要在不同時間使用不同的 CDN 執行個體。You may need to use different CDN instances at various times. 例如,當您部署新版的應用程式時,可能會想要使用新的 CDN,並保留舊的 CDN (以適用於舊版的舊格式保存內容)。For example, when you deploy a new version of the application you may want to use a new CDN and retain the old CDN (holding content in an older format) for previous versions. 如果您將 Azure Blob 儲存體作為內容的原點,可以建立個別的儲存體帳戶或個別的容器,並將 CDN 端點指向它。If you use Azure blob storage as the content origin, you can create a separate storage account or a separate container and point the CDN endpoint to it.

請勿使用查詢字串來表示 CDN 上資源連結中不同版本的應用程式,因為從 Azure Blob 儲存體擷取內容時,查詢字串為資源名稱 (Blob 名稱) 的一部分。Do not use the query string to denote different versions of the application in links to resources on the CDN because, when retrieving content from Azure blob storage, the query string is part of the resource name (the blob name). 此方法也會影響用戶端快取資源的方式。This approach can also affect how the client caches resources.

若是在 CDN 上快取先前的資源,則在部署新版本的靜態內容時,更新應用程式可能是一項挑戰。Deploying new versions of static content when you update an application can be a challenge if the previous resources are cached on the CDN. 如需詳細資訊,請參閱以下與快取控制有關的小節。For more information, see the section on cache control, below.

考慮依據國家/地區限制 CDN 內容存取。Consider restricting the CDN content access by country/region. Azure CDN 可讓您根據來源的國家或地區來篩選要求,並限制傳遞的內容。Azure CDN allows you to filter requests based on the country or region of origin and restrict the content delivered. 如需詳細資訊,請參閱 依國家/地區限制對內容的存取For more information, see Restrict access to your content by country/region.

快取控制Cache control

請考量如何管理系統內的快取。Consider how to manage caching within the system. 例如,在 Azure CDN 中,您可以設定全域快取規則,然後為特定的來源端點設定自訂快取。For example, in Azure CDN, you can set global caching rules, and then set custom caching for particular origin endpoints. 您也可以在來源傳送快取指示詞標頭,以控制在 CDN 中執行快取的方式。You can also control how caching is performed in a CDN by sending cache-directive headers at the origin.

如需詳細資訊,請參閱快取的運作方式For more information, see How caching works.

若要防止在 CDN 上使用物件,您可以從來源加以刪除、移除或刪除 CDN 端點,或在使用 Blob 儲存體的情況下,讓容器或 Blob 變成私用。To prevent objects from being available on the CDN, you can delete them from the origin, remove or delete the CDN endpoint, or in the case of blob storage, make the container or blob private. 不過,在存留時間到期之前,不會從 CDN 中移除專案。However, items are not removed from the CDN until the time-to-live expires. 您也可以手動清除 CDN 端點。You can also manually purge a CDN endpoint.

安全性Security

CDN 可以使用 CDN 所提供的憑證,透過 HTTPS (SSL) 傳遞內容,也可以透過 HTTP。The CDN can deliver content over HTTPS (SSL), by using the certificate provided by the CDN, as well as over standard HTTP. 為了避免瀏覽器發出混合內容警告,您最好使用 HTTPS,要求透過 HTTPS 載入的頁面所顯示的靜態內容。To avoid browser warnings about mixed content, you might need to use HTTPS to request static content that is displayed in pages loaded through HTTPS.

使用 CDN 傳遞靜態資產時 (如字型檔案),如果使用 XMLHttpRequest 呼叫要求不同網域中的這些資源,可能會遇到相同來源原則問題。If you deliver static assets such as font files by using the CDN, you might encounter same-origin policy issues if you use an XMLHttpRequest call to request these resources from a different domain. 許多網頁瀏覽器會防止跨原始來源資源分享 (CORS),除非網頁伺服器已設定適當的回應標頭。Many web browsers prevent cross-origin resource sharing (CORS) unless the web server is configured to set the appropriate response headers. 使用下列方法之一可以設定 CDN 支援 CORS:You can configure the CDN to support CORS by using one of the following methods:

CDN 後援CDN fallback

考量應用程式如何處理 CDN 失敗或暫時無法使用。Consider how your application will cope with a failure or temporary unavailability of the CDN. 如果無法使用 CDN,用戶端應用程式可使用前一個要求期間的本機快取資源複本 (位於用戶端),或者可以加入程式碼來偵測失敗,而非從原點要求資源 (應用程式資料夾或佔用資源的 Azure Blob 容器)。Client applications may be able to use copies of the resources that were cached locally (on the client) during previous requests, or you can include code that detects failure and instead requests resources from the origin (the application folder or Azure blob container that holds the resources) if the CDN is unavailable.