Created
May 24, 2020 18:58
-
-
Save TanAlex/3c15fd01a2bf7e054308869e11651a6a to your computer and use it in GitHub Desktop.
lambda@edge function handle 404,403 response from s3 origin
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
'use strict'; | |
const http = require('https'); | |
const indexPage = 'index.html'; | |
exports.handler = async (event, context, callback) => { | |
const cf = event.Records[0].cf; | |
const request = cf.request; | |
const response = cf.response; | |
const statusCode = response.status; | |
// Only replace 403 and 404 requests typically received | |
// when loading a page for a SPA that uses client-side routing | |
const doReplace = request.method === 'GET' | |
&& (statusCode == '403' || statusCode == '404'); | |
if (doReplace){ | |
let appPath = getAppPath(request.uri); | |
let appPathLower = appPath.toLowerCase(); | |
if (appPath && appPathLower != 'api')){ | |
response.status = '301'; | |
response.statusDescription = 'Found'; | |
response.body = ''; | |
let redirect_path = "/index.html"; | |
if (appPathLower == 'admin' || appPathLower == 'reports'){ | |
redirect_path = "/"+appPath+"/index.html"; | |
} | |
if (! response.headers){ | |
response.headers = {}; | |
} | |
response.headers['location'] = [{ key: 'Location', value: redirect_path }]; | |
} | |
} | |
callback(null, response); | |
}; | |
// Get the app path segment | |
function getAppPath(path){ | |
if(!path){ | |
return ''; | |
} | |
if(path[0] === '/'){ | |
path = path.slice(1); | |
} | |
const segments = path.split('/'); | |
return segments[0]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment