You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用CloudFront Function重写源站URL而非执行重定向?

CloudFront Function 实现源站URL修改(无浏览器URL变化)

当前问题场景

你目前使用CloudFront Function通过307重定向实现URL跳转,代码如下:

return {
  statusCode: 307,
  statusDescription: 'Found',
  headers: { location: { value: $newUrl } },
}

但这种方式会导致浏览器地址栏显示的URL被修改。尝试直接修改host头来实现内部转发:

request.headers.host.value=$newUrl;

执行后触发错误:

The CloudFront function tried to add, delete, or change a read-only header.
We can't connect to the server for this app or website at this time.
There might be too much traffic or a configuration error.
Try again later, or contact the app or website owner.

解决方案:修改源站配置而非Host头

CloudFront Function中request.headers.host属于只读头部,无法直接修改。但你可以通过修改request.origin属性来实现内部源站转发,这种方式不会改变浏览器显示的URL。

示例代码如下:

function handler(event) {
  const request = event.request;
  // 替换为你的目标源站域名
  const targetOriginDomain = "your-target-origin.com";

  // 修改源站域名
  request.origin.custom.domainName = targetOriginDomain;
  // 根据源站配置设置协议(http/https)
  request.origin.custom.protocol = "https";

  // 可选:如果需要修改请求路径,可调整request.uri
  // request.uri = "/new-base-path" + request.uri;

  return request;
}

关键说明

  • 这种方式是CloudFront内部将请求转发到新的源站,浏览器端不会感知到URL变化,避免了重定向带来的地址栏变更。
  • 确保目标源站允许CloudFront的IP访问(可通过源站安全组或防火墙配置)。
  • 如果你的源站是S3等AWS托管服务,需对应调整request.origin.s3相关属性,而非request.origin.custom。

内容的提问来源于stack exchange,提问作者Joey Yi Zhao

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 18:14:53