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

请求修改JavaScript响应头脚本,支持按特定URI添加自定义响应头

Solution for URI-Specific Custom Response Headers

Perfect, let's tweak your script to handle URI-specific custom headers while retaining the existing X-Robots-Tag functionality. The goal is to make this easy to scale later—so adding new URI-header pairs won't require rewriting core logic.

Here's the updated code:

'use strict';
exports.handler = (event, context, callback) => {
    // Get contents of response and request URI
    const response = event.Records[0].cf.response;
    const headers = response.headers;
    const uri = event.Records[0].cf.request.uri; // Use request.uri for reliable original request path

    // Scalable mapping: add new URI-header pairs here later
    const uriHeaderMappings = {
        '/ads': { 'X-Ads-Tag': 'true' },
        '/marketing': { 'X-Marketing-Tag': 'true' }
        // Example future addition:
        // '/promotions': { 'X-Promo-Tag': 'active' }
    };

    // Keep the global X-Robots-Tag for all requests
    headers['X-Robots-Tag'] = [{ key: 'X-Robots-Tag', value: 'noindex' }];

    // Apply custom header if current URI matches our mapping
    if (uriHeaderMappings[uri]) {
        const customHeaders = uriHeaderMappings[uri];
        Object.entries(customHeaders).forEach(([headerKey, headerValue]) => {
            headers[headerKey.toLowerCase()] = [{ key: headerKey, value: headerValue }];
            // CloudFront normalizes header keys to lowercase—this ensures consistency
        });
    }

    callback(null, response);
};

Key Details:

  • Easy Scalability: All URI-to-header rules live in the uriHeaderMappings object. To add new pairs later, just drop in a new key-value entry here without touching the rest of the logic.
  • Reliable URI Matching: I switched to request.uri instead of response.uri because it represents the original path the user requested (response URIs can sometimes be modified by edge logic, making them less reliable for matching).
  • Header Consistency: CloudFront automatically normalizes header keys to lowercase, so we convert custom header keys to lowercase when adding them to avoid mismatches.
  • Preserved Original Logic: The global X-Robots-Tag: noindex is still applied to every request, just like your original script intended.

内容的提问来源于stack exchange,提问作者paquino

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 10:52:30