在Cloudfront的控制台中,创建一个新的“行为”,并将“协议策略”设置为“HTTP和HTTPS”。
在你的robots.txt文件中添加以下代码:
User-agent: * Disallow:
'use strict'; exports.handler = (event, context, callback) => { //获取请求的URL和User-Agent标头 const request = event.Records[0].cf.request; const headers = request.headers;
//检查User-Agent是否为搜索引擎的机器人 const userAgent = headers['user-agent'][0].value; const isRobotUA = /bot|crawler|spider|google|baidu|bing|msn|yandex|facebook|twitter/i.test(userAgent);
//检查是否为robots.txt文件,并且不是机器人访问 const isRobotsTxt = request.uri.endsWith('/robots.txt'); if (isRobotsTxt && !isRobotUA) { const response = { status: '403', statusDescription: 'Forbidden', body: 'This file is for search engine robots only', headers: { 'cache-control': [{ key: 'Cache-Control', value: 'max-age=31536000' }], 'content-type': [{ key: 'Content-Type', value: 'text/plain; charset=utf-8' }] } }; callback(null, response); }
//如果不是robots.txt文件或者访问者是机器人,则将请求传递给Cloudfront callback(null, request); };
这段代码将检查User-Agent标头是否表示一个机器人,并且仅当此请求来自机器人时才阻止机器人访问robots.txt文件。这将解决由Cloudfront地理限制引起的问题,因为机器人现在可以使用robots.txt文件来发现站点上的所有受限制的URLS。
上一篇:避免CI中的冗余构建和测试
下一篇:避免CloudSQL高日费用