

文档 AWS SDK 示例 GitHub 存储库中还有更多 [S AWS DK 示例](https://github.com/awsdocs/aws-doc-sdk-examples)。

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 将 HTTP 安全标头添加到 CloudFront 函数查看器响应事件
<a name="cloudfront_example_cloudfront_functions_add_security_headers_section"></a>

以下代码示例说明如何向 CloudFront 函数查看器响应事件添加 HTTP 安全标头。

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

**JavaScript CloudFront 函数的运行时 2.0**  
 还有更多相关信息 GitHub。在 Functions 示例存储库中查找完整的[示例](https://github.com/aws-samples/amazon-cloudfront-functions/tree/main/add-security-headers)并学习如何设置和运行。CloudFront 

```
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;
}
```

------