Using Cloudfront Function for redirect of specific path

0

I'm trying to use the new CF Functions to redirect a specific URL that we have hardcoded incorrectly in our product. The function tests are successful, but requests to the distribution do not seem to get modified as expected.
Here's my scenario:
Bad path that is hardcoded: http://mybucket.s3.amazonaws.com/programs/productname/xxx-xxx-gt/file1.txt
Correct path to redirect to: http://mybucket.s3.amazonaws.com/programs/productname/18/file1.txt

I created a new function. Tested the function (using Test tab in UI) to make sure "/programs/productname/xxx-xxx-gt" is rewritten as "/programs/productname/18". I published the function to Live. I associated the function with my distribution "mybucket" with Event Type = Viewer Request, and Cache behavior = Default(*).

However, when I browse to http://mybucket.s3.amazonaws.com/programs/productname/xxx-xxx-gt/file1.txt. I get the typical "AccessDenied" XML response since that file does not exist at that path. But I would expect the Function to have pulled the file from the correct path.

Any idea why this function tests OK but does not work from my browser?

Here is the Function (modified from the GitHub example):

function handler(event) {
var request = event.request;
var uri = request.uri;

// Check whether the URI is using the bad path.  
if (uri.includes('xxx-xxx-gt')) {  
    request.uri = '/programs/product/18/file1.txt';  
}   
return request;  

}

Edited by: GSI-dennis on May 11, 2021 4:46 PM

Edited by: GSI-dennis on May 11, 2021 4:48 PM

asked 3 years ago4802 views
1 Answer
0

I solved this problem.
First, I had associated the function with the wrong distribution.
Second, to make a change to one directory in the path, I used the following function:

function handler(event) {
var request = event.request;
var uri = request.uri;
//Check whether the URI is bad.
if (uri.includes('xxx-xxx-gt')) {
var uriArray = request.uri.split('/');
//Change the bad dir to the '18' dir in the URI
uriArray[3] = 18;
request.uri = uriArray.join('/');
}
return request;
}

I hope this helps someone else.

answered 3 years ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions