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

已提問 3 年前檢視次數 4864 次
1 個回答
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.

已回答 3 年前

您尚未登入。 登入 去張貼答案。

一個好的回答可以清楚地回答問題並提供建設性的意見回饋,同時有助於提問者的專業成長。

回答問題指南