AWS cloudfront 添加自定义 header 而不使用 Lambda@Edge

AWS cloudfront add custom header without using Lambda@Edge

我想将 x-frame-options 作为 sameorigin 添加到 AWS CloudFrontS3 存储桶上为我的应用程序提供服务的服务。

我不想添加新的 Lambda 函数来编辑请求 header。

其实我在附件下面找到了一个地方:

CloudFront 分发 -> 我的分发设置 -> 起源和起源组 -> 代表我的应用程序的 S3 内容项 -> 添加起源自定义 Headers -> Header 名称:x-frame-options,值:同源

但是当部署即将完成时,在 S3 存储桶文件和 URL 的所有相关请求中仍然会变老 header。

如何在没有任何 Lambda 函数的情况下直接使用现有的 AWS CloudFront 面板添加到 headers?

您正在配置的 "Origin Custom Headers" 不是 header,它们会添加到源的响应中,而是添加到对源发出的请求中。来自 CloudFront documentation:

You can configure CloudFront to add custom headers to the requests that it sends to your origin. These custom headers enable you to send and gather information from your origin that you don’t get with typical viewer requests. These headers can even be customized for each origin. CloudFront supports custom headers for both for custom and Amazon S3 origins.

因此没有添加响应 header 的选项。虽然存在 use S3 metadata 影响返回给查看者的 header 的可能性,但这仅适用于 Content-Type-header,因此这不是一个选项。

最好的选择是使用 Lambda@Edge 函数。虽然这听起来像是一个麻烦且昂贵的解决方案,但实际上并非如此。对于您的用例,该 Lambda@Edge 函数的代码可以如下所示简单:

def lambda_handler(event, context):
    response = event["Records"][0]["cf"]["response"]
    response["headers"]["x-frame-options"] = ":sameorigin"
    return response

当您将此 Lambda@Edge 函数配置为触发 CloudFront 中的 "Origin Response" 事件时,它不会针对每个查看器请求执行,而是仅在未缓存返回给查看器的内容时​​执行由 CloudFront 提供,必须先从 S3 获取。这有助于最大程度地减少执行 Lambda@Edge 函数引起的额外延迟和成本。

This SO answer帮了我,但我先发现了这个问题,所以也在这里分享答案。

您现在可以通过 CloudFront Functions 设置 headers,而不必创建 Lambda@Edge 函数。文档中提供的示例代码非常适合设置过时的浏览器安全性所需的 headers:

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'"}; 
    headers['x-content-type-options'] = { value: 'nosniff'}; 
    headers['x-frame-options'] = {value: 'DENY'}; 
    headers['x-xss-protection'] = {value: '1; mode=block'}; 

    // Return the response to viewers 
    return response;
}

截至 2021 年 11 月,Cloudfront 现已支持 Response Headers Policies。这允许您将一个策略与您的分配相关联,该分配定义了要返回的额外响应 headers。如果您不想使用完整的安全 Headers 固定策略,您可以创建一个仅包含 x-frame-options.

的自定义策略