Created
January 27, 2019 23:29
-
-
Save danquack/9a1d200d621fa4af12ca33001f1a3719 to your computer and use it in GitHub Desktop.
Lambda function to dynamically route traffic if user-agent is crawler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Credit: https://github.com/jinty/prerender-cloudfront | |
// Credit: https://aws.amazon.com/blogs/networking-and-content-delivery/dynamically-route-viewer-requests-to-any-origin-using-lambdaedge/ | |
exports.handler = (event, context, callback) => { | |
const request = event.Records[0].cf.request; | |
const headers = request.headers; | |
const user_agent = headers['user-agent']; | |
if (user_agent) { | |
var prerender = /googlebot|bingbot|yandex|baiduspider|Facebot|facebookexternalhit|twitterbot|rogerbot|linkedinbot|embedly|quora link preview|showyoubot|outbrain|pinterest|slackbot|vkShare|W3C_Validator/i.test(user_agent[0].value); | |
prerender = prerender || /_escaped_fragment_/.test(request.querystring); | |
prerender = prerender && ! /\.(css|xml|less|png|jpg|jpeg|gif|pdf|doc|txt|ico|rss|zip|mp3|rar|exe|wmv|doc|avi|ppt|mpg|mpeg|tif|wav|mov|psd|ai|xls|mp4|m4a|swf|dat|dmg|iso|flv|m4v|torrent|ttf|woff|svg|eot)$/i.test(request.uri); | |
if (prerender) { | |
// if a query string provided remove the query string and replace the ? with a + (translated to space with S3) | |
if (request.querystring) { | |
request.uri += `+${request.querystring}`; | |
request.querystring = '' | |
} | |
// Return the prerendering bucket to S3 | |
const s3DomainName = process.env.s3DomainName; | |
request.origin = { | |
s3: { | |
domainName: s3DomainName, | |
region: '', | |
authMethod: 'none', | |
path: '', | |
customHeaders: {} | |
} | |
}; | |
request.headers['host'] = [{ key: 'host', value: s3DomainName }]; | |
console.log(user_agent[0].value, "requesting", request.uri); | |
} | |
} | |
callback(null, request); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment