

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 將 HTTP 安全標頭新增至 CloudFront Functions 檢視器回應事件
<a name="example_cloudfront_functions_add_security_headers_section"></a>

下列程式碼範例示範如何將 HTTP 安全標頭新增至 CloudFront Functions 檢視器回應事件。

------
#### [ JavaScript ]

**適用於 CloudFront Functions 的 JavaScript 執行時期 2.0 功能**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [CloudFront Functions 範例](https://github.com/aws-samples/amazon-cloudfront-functions/tree/main/add-security-headers)儲存庫中設定和執行。

```
async function handler(event) {
    var response = event.response;
    var headers = response.headers;

    // Set HTTP security headers
    // Since JavaScript doesn't allow for hyphens in variable names, we use the dict["key"] notation 
    headers['strict-transport-security'] = { value: 'max-age=63072000; includeSubdomains; preload'}; 
    headers['content-security-policy'] = { value: "default-src 'none'; img-src 'self'; script-src 'self'; style-src 'self'; object-src 'none'; frame-ancestors 'none'"}; 
    headers['x-content-type-options'] = { value: 'nosniff'}; 
    headers['x-frame-options'] = {value: 'DENY'}; 
    headers['x-xss-protection'] = {value: '1; mode=block'};
    headers['referrer-policy'] = {value: 'same-origin'};
    
    // Return the response to viewers 
    return response;
}
```

------

如需 AWS SDK 開發人員指南和程式碼範例的完整清單，請參閱 [搭配 AWS SDK 使用 CloudFront](sdk-general-information-section.md)。此主題也包含有關入門的資訊和舊版 SDK 的詳細資訊。