请求修改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
uriHeaderMappingsobject. 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.uriinstead ofresponse.uribecause 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: noindexis still applied to every request, just like your original script intended.
内容的提问来源于stack exchange,提问作者paquino
相关产品推荐
相关产品推荐

