Cloudfront redirect for S3 subdirectories

Viewed 56

I have a S3 bucket with multiple directories /experiment1, experiment2, etc. Inside each one of these directories lives a static application with the relevant files (index.html, js bundles). Each one of these apps have their own in app SPA router to handle routing.

The routing for access these apps are relatively straightforward for the index.html, going to https://blahblah.com/experiment1/ works as expected, rendering the app. The problem is when it goes deeper than the directory root. For example, going to https://blahblah.com/experiment1/about will give a 404, because naturally that file does not exist on S3. In the past when there's only one "App" in an S3 bucket, a redirect of the 404 origin response to /index.html in Cloudfront has worked. In this case this won't work because i need to redirect dynamically to /experiment*/index.html. Below is a Lambda@Edge configuration i've tried but have not successfully gotten it to work.

Any help is appreciated

exports.handler = (event, context, callback) => {
    'use strict';
    const response = event.Records[0].cf.response;
    // grabs the experiment1 part of /experiment1/about
    const firstPath = response.uri.split('/')[1];
    
    if (response.status == 404) {
        
        //Response Status Code and Description
        response.status = 200;
        response.statusDescription = 'OK';
        
        response.body = '';
        
        //Set the Redirect Location
        response.headers['location'] = [{ key: 'Location', value: `/${firstPath}/index.html` }];
    }
    callback(null, response);
};

This config just gives me a blank page, with a status of 200

1 Answers

Use HTTP status code 302 to indicate a temporary redirect instead of status code 200 which indicates success.

response.status = 302;
response.statusDescription = 'Found';
Related